R语言 多总体直方图

webghufk  于 2023-11-14  发布在  其他
关注(0)|答案(3)|浏览(151)

我感兴趣的是在R中创建一个直方图,它将包含两个(或更多)相互重叠的人口,这意味着-我不希望两个直方图共享同一个图,而是一个包含两种或更多种颜色的条形图。
找到下面的图片-这是我想完成的。
x1c 0d1x的数据
有什么想法吗?

kyks70gy

kyks70gy1#

这实际上是ggplot2中令人讨厌的默认值:

library(ggplot2)
ggplot(iris, aes(x=Sepal.Length, fill=Species)) +
  geom_histogram()

字符串


的数据

lg40wkob

lg40wkob2#

下面是另一个不使用ggplot的选项:

#plot the entire data set (everything)
hist(everything, breaks=c(1:10), col="Red")

#then everything except one sub group (1 in this case)
hist(everything[everything!=1], breaks=c(1:10), col="Blue", add=TRUE)

#then everything except two sub groups (1&2 in this case)
hist(everything[everything!=1 && everything!=2], breaks=c(1:10), col="Green", add=TRUE)

字符串

xzv2uavs

xzv2uavs3#

# 1) Define the breaks to use on your Histogram
xrange = seq(-3,3,0.1)

# 2) Have your vectors ready
v1 = rnorm(n=300,mean=1.1,sd=1.5)
v2 = rnorm(n=350,mean=1.3,sd=1.5)
v3 = rnorm(n=380,mean=1.2,sd=1.9)

# 3) subset your vectors to be inside xrange
v1 = subset(v1,v1<=max(xrange) & v1>=min(xrange))
v2 = subset(v2,v2<=max(xrange) & v2>=min(xrange))
v3 = subset(v3,v3<=max(xrange) & v3>=min(xrange))

# 4) Now, use hist to compute the counts per interval
hv1 = hist(v1,breaks=xrange,plot=F)$counts
hv2 = hist(v2,breaks=xrange,plot=F)$counts
hv3 = hist(v3,breaks=xrange,plot=F)$counts

# 5) Finally, Generate a Frequency BarPlot that is equivalent to a Stacked histogram
maintitle = "Stacked Histogram Example using Barplot"
barplot(rbind(hv1,hv2,hv3),col=2:4,names.arg=xrange[-1],space=0,las=1,main=maintitle)

# 6) You can also generate a Density Barplot
Total = hv1 + hv2 + hv3
barplot(rbind(hv1/Total,hv2/Total,hv3/Total),col=2:4,names.arg=xrange[-1],space=0,las=1)

字符串

相关问题