2015-05-12 38 views
9

,我有以下的數據幀:GGPLOT2:劇情意味着與geom_bar

test2 <- data.frame(groups = c(rep("group1",4), rep("group2",4)), 
    X2 = c(rnorm(4), rnorm(4)) , 
    label = c(rep(1,2),rep(2,2),rep(1,2),rep(2,2))) 

,我使用繪製條形圖每組每個標籤:

ggplot(test2, aes(label, X2, fill=as.factor(groups))) + 
    geom_bar(position="dodge", stat="identity") 

enter image description here

然而,我似乎無法找到stat="mean",因此我可以在每個條形圖上繪製手段而不是標識。

感謝您的任何幫助。

+0

本教程提供瞭如何很好的說明要實現這一點:http://www.r-bloggers.com/using-r-barplot-with-ggplot2/ – seaotternerd

+1

可能重複[繪製ggplot2中每個級別的平均值](http://stackoverflow.com/questions/11857935/plotting-the-average-values-for-each-level-in-ggplot2) – seaotternerd

回答

29

繪製簡單地使用stat = "summary"fun.y = "mean"

ggplot(test2) + 
    geom_bar(aes(label, X2, fill = as.factor(groups)), 
      position = "dodge", stat = "summary", fun.y = "mean") 

enter image description here

+0

哇!真棒,真的很高雅。謝謝!你碰巧知道如何以更好的方式獲得更深的顏色? – Cauchy

2

ggplot2對於1個陰謀點喜歡1個數據點。創建您的彙總統計新的數據幀,然後用stat="identity"

require(reshape2) 
plot.data <- melt(tapply(test2$X2, test2$groups,mean), varnames="group", value.name="mean") 

ggplot(plot.data, aes(x=group,y=mean)) + geom_bar(position="dodge", stat="identity") 

enter image description here