2014-10-28 30 views
9

我有興趣在R中創建一個直方圖,它將包含兩個(或更多)羣體,這意味着 - 我不希望兩個直方圖共享相同的圖形,而是一個條形圖包含兩種顏色或更多。R具有多個羣體的直方圖

找到下面的圖像 - 這是我想要完成的。

example

任何想法?

+0

這是一個堆疊條形圖/圖。在這裏有很多例子像stackoverflow像http://stackoverflow.com/questions/21236229/ggplot2-stacked-bar-chart和http://stackoverflow.com/questions/6693257/making-a-stacked-bar-plot-換多變量 - GGPLOT2式-R。如果您顯示一些數據/可重複的數據示例,它可以幫助其他人幫助您。 – 2014-10-28 15:59:02

+0

看看'?barplot'。例如。 'barplot(VADeaths,legend = rownames(VADeaths))'。 – jbaums 2014-10-28 16:05:14

回答

12

那其實是GGPLOT2惱人默認:

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

resulting plot

2
# 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) 
+0

很好的答案!我想提出兩點建議,讓您的密度陰謀傳統,更一般。使用Total = sum(hv1,hv2,hv3)'來創建一個傳統的密度直方圖,其中所有小節的值總和爲1,而不是每個小節加總爲1.要校正潛在不等寬的bin,請使用'rbind(hv1 /(Total * diff(xrange),hv2 /(Total * diff(xrange),hv3 /(Total * diff(xrange))''。 – 2016-06-27 20:54:25

2

這裏是不使用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)