如何在ggplot中的直方图条顶部打印频率

时间:2021-06-10 17:49:41

标签: r ggplot2 r-markdown histogram knitr

我想知道是否可以在 ggplot 直方图中显示每个计数条顶部的频率。

这是我目前得到的代码:

br <- seq(0, 178, 10)
ggplot(dfAllCounts, aes(x=months)) + geom_histogram(aes(months), bins = 30, fill="#d2aa47", color = '#163B8B', size = .8, alpha = 0.3) + 
  scale_x_continuous(breaks = br)

我想在顶部显示那个月数,谢谢

1 个答案:

答案 0 :(得分:0)

切换到底层的 stat_bin 函数,而不是 geom_histogram 包装器,您可以在其中使用内置的 geom="text",结合 after_stat(count) 将标签添加到直方图。

ggplot(mpg,aes(x=displ)) + 
  stat_bin(binwidth=1) +
  stat_bin(binwidth=1, geom="text", aes(label=after_stat(count)), vjust=0) 

修改自 https://stackoverflow.com/a/24199013/10276092

相关问题