问题描述
我正在尝试使用ggplot2做一个简单的图:
I'm trying to do a simple plot using 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))
如何注释此图,以便在条上方获得注释?现在,geom_text将标签放在条形图的底部,但我希望它们在这些条形图上方.
How can I annotate this plot so that I get annotations above bars? Now geom_text puts labels at the bottom of the bars, but I want them above these bars.
推荐答案
您可以使用stat_summary()
计算y
值的位置作为depth
之和,并使用geom="text"
添加标签.使用总和是因为条形图显示每个cut
值的depth
值总和.
You can use stat_summary()
to calculate position of y
values as sum of depth
and use geom="text"
to add labels. The sum is used because your bars shows the sum of depth
values for each cut
value.
如@joran所建议,最好使用stat_summary()
而不是geom_bar()
来显示y值的总和,因为stat="identity"
由于小节的过度绘图会出现问题,如果出现负值,则小节将开始于图的负数部分,以正数结尾-结果将不是实际值的总和.
As suggest by @joran it is better to use stat_summary()
instead of geom_bar()
to show sums of y values because stat="identity"
makes problems due to overplotting of bars and if there will be negative values then bar will start in negative part of plot and end in positive part - result will be not the actual sum of values.
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)
您还可以预先计算深度值的总和,并且可以将geom_bar()
与stat="identity"
和geom_text()
一起使用.
You can also precalculate sum of depth values and the you can use geom_bar()
with stat="identity"
and 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)
这篇关于如何在栏上方注释geom_bar?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!