ggplot2:如何总结计数? stat_summary或​​stat_bin

时间:2014-03-19 08:55:01

标签: r plot count ggplot2

我使用ggplot2来计算和汇总数据框中每种模式的出现次数。 testdata $ V5是4种不同模式的因素。 testdata中的每一行都有一个模式条目,我想要计算它们。

p <- ggplot(testdata,aes(V5))
p = p + geom_histogram()
show(p)

此代码生成以下图表:

produced plot

我现在正试图在显示计数的每个条形图顶部显示文本标签,但我不太清楚如何使用stat_summary实现这一点。如何在显示计数的每个x值栏的顶部生成文本标签?

我试过

p <- ggplot(testdata,aes(V5))
p = p + geom_histogram()
p = p + stat_summary(fun.data=count, geom="text", size=20, color="red") #<-- no effect
show(p)

但它没有任何吸引力。

1 个答案:

答案 0 :(得分:3)

您可以使用&#34;隐藏&#34;变量..count..geom_text结合使用:

p + 
  geom_histogram() + 
  stat_bin(aes(label=..count..), geom="text", position="identity", size=20, color="red")

geom_text也有hjustvjust参数可能会有所帮助。