如何在栏上方注释geom_bar?

时间:2013-11-26 19:44:08

标签: r ggplot2

我正在尝试使用ggplot2做一个简单的情节:

library(ggplot2)

ggplot(diamonds, aes(x = cut, y = depth)) + 
  geom_bar(stat = "identity", color = "blue") +
  facet_wrap(~ color) +
  geom_text(aes(x = cut, y = depth, label = cut, vjust = 0))

ggplot2 plot

如何对这个情节进行注释,以便我在条形图上方获得注释?现在geom_text将标签放在条形图的底部,但我希望它们位于这些条形图上方。

1 个答案:

答案 0 :(得分:5)

您可以使用stat_summary()计算y值的位置作为depth的总和,并使用geom="text"添加标签。使用总和是因为您的条形显示每个depth值的cut值的总和。

根据@joran的建议,最好使用stat_summary()代替geom_bar()来显示y值的总和,因为stat="identity"由于条形图的过度绘制而产生问题,以及是否会出现负面影响值然后bar将从图的负部分开始并以正部分结束 - 结果将不是实际值的总和。

ggplot(diamonds[1:100,], aes(x = cut, y = depth)) + 
  facet_wrap(~ color) + 
  stat_summary(fun.y = sum, geom="bar", fill = "blue", aes(label=cut, vjust = 0)) + 
  stat_summary(fun.y = sum, geom="text", aes(label=cut), vjust = 0) 

enter image description here

您还可以预先计算深度值的总和,并将geom_bar()stat="identity"geom_text()一起使用。

library(plyr)
diamonds2<-ddply(diamonds,.(cut,color),summarise,depth=sum(depth))

ggplot(diamonds2,aes(x=cut,y=depth))+
  geom_bar(stat="identity",fill="blue")+
  geom_text(aes(label=cut),vjust=0,angle=45,hjust=0)+
  facet_wrap(~color)
相关问题