多总体R直方图

多总体R直方图,r,graphics,histogram,R,Graphics,Histogram,我感兴趣的是在R中创建一个直方图,它将包含两个(或更多)相互重叠的总体,这意味着-我不希望两个直方图共享同一个图形,而是一个包含两种或更多颜色的条 找到下面的图片-这是我想要完成的 有什么想法吗 这实际上是ggplot2中恼人的默认设置: library(ggplot2) ggplot(iris, aes(x=Sepal.Length, fill=Species)) + geom_histogram() #1)定义要在直方图上使用的断点 xrange=序列(-3,3,0.1) #2)准备

我感兴趣的是在R中创建一个直方图,它将包含两个(或更多)相互重叠的总体,这意味着-我不希望两个直方图共享同一个图形,而是一个包含两种或更多颜色的条

找到下面的图片-这是我想要完成的


有什么想法吗

这实际上是ggplot2中恼人的默认设置:

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

#1)定义要在直方图上使用的断点
xrange=序列(-3,3,0.1)
#2)准备好向量
v1=rnorm(n=300,平均值=1.1,标准差=1.5)
v2=rnorm(n=350,平均值=1.3,标准差=1.5)
v3=rnorm(n=380,平均值=1.2,标准差=1.9)
#3)将向量子集为X范围内
v1=子集(v1,v1=最小值(X范围))
v2=子集(v2,v2=最小值(X范围))
v3=子集(v3,v3=最小值(xrange))
#4)现在,使用hist计算每个间隔的计数
hv1=历史(v1,中断=X范围,绘图=F)$计数
hv2=历史(v2,中断=X范围,绘图=F)$计数
hv3=历史(v3,中断=X范围,绘图=F)$计数
#5)最后,生成与叠加直方图等效的频率条形图
mainttitle=“使用条形图的堆叠直方图示例”
条形图(rbind(hv1,hv2,hv3),col=2:4,names.arg=xrange[-1],space=0,las=1,main=mainttitle)
#6)还可以生成密度条形图
总计=hv1+hv2+hv3
条形图(rbind(hv1/Total,hv2/Total,hv3/Total),col=2:4,names.arg=xrange[-1],space=0,las=1)

这里是不使用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)

这是一个堆叠的条形图/图表。这里有许多关于stackoverflow的例子,比如和。如果您展示了一些数据/数据的可复制示例,这将有助于其他人帮助您。请查看
?条形图
。例如,
barplot(vadeath,legend=rownames(vadeath))
。回答得好!我想提出两个建议,使你的密度图更传统,更一般。使用
Total=sum(hv1,hv2,hv3)
制作传统的密度直方图,其中所有条的值总和为1,而不是每个条的总和为1。要纠正宽度可能不相等的箱子,请使用
rbind(hv1/(Total*diff(xrange)、hv2/(Total*diff(xrange)、hv3/(Total*diff(xrange))
。这是一个时髦的解决方案:)
#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)