如何在栏上方注释geom_bar?

jra*_*ara 2 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))
Run Code Online (Sandbox Code Playgroud)

ggplot2图

如何注释此图,以便在条上方获得注释?现在geom_text将标签放在条形图的底部,但我希望它们在这些条形图上方。

Did*_*rts 5

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

正如@joran所建议的那样,最好使用stat_summary()而不是geom_bar()显示y值的总和,因为stat="identity"由于柱形图的过度绘制会造成问题,如果出现负值,则柱形图将从图形的负数部​​分开始并以正数部分结束-结果将是不是实际的价值总和。

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) 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

您还可以预先计算深度值的总和,并且可以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)
Run Code Online (Sandbox Code Playgroud)

  • 这似乎可行:ggplot(钻石,aes(x =切割,y =深度))+ facet_wrap(〜颜色)+ 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) (2认同)