ggplot:将百分比添加到条形图

时间:2016-04-27 21:39:51

标签: r ggplot2

我们假设我们创建了一个条形图,我们希望显示落入给定类别的百分比。我正在考虑调查数据,并显示有多少人对A,B或C做出响应并执行此操作而无需更改数据。

示例代码:

data(mtcars)
ggplot(data=mtcars, aes(hp))+
  geom_bar(aes(y = (..count..)/sum(..count..)), binwidth = 25) + 
    scale_y_continuous(labels=percent)

现在如何添加百分比标签?我尝试了很多不同的方法,看过很多人发布的内容,但没有运气。

1 个答案:

答案 0 :(得分:1)

一种方法:您可以将stat_bingeom="text"

一起使用
data(mtcars)
ggplot(data=mtcars, aes(hp))+
  geom_histogram(aes(y = (..count..)/sum(..count..)), binwidth = 25) + 
  stat_bin(aes(y = (..count..)/sum(..count..), 
               label=scales::percent((..count..)/sum(..count..))), 
           geom="text", binwidth = 25, vjust=-.2)

enter image description here

相关问题