[英]Show percent of total on top of geom_bar in ggplot2 while showing counts on y axis
我正在尝试使用ggplot2创建条形图,显示y轴上的计数,但也显示每个条形顶部的总计百分比。 我已经计算了总数的计数和百分比,但无法弄清楚如何在条形图的顶部添加百分比。 我正在尝试使用geom_text,但无法使其正常工作。
一个最小的例子:
iris %>%
group_by(Species) %>%
summarize(count = n()) %>%
mutate(percent = count/sum(count)) %>%
ggplot(aes(x=Species, y=count)) +
geom_bar(stat="identity") +
geom_text(aes(label = scales::percent(..prop..), y=..count..), stat= "count", vjust = -.5)
我看过其他答案,例如如何在百分比条形图上方添加百分比或计数标签? ,但在这些示例中,y轴和标签都显示百分比。 我试图显示y轴上的计数和标签中的百分数。
library(dplyr)
library(ggplot2)
df1 = iris %>%
group_by(Species) %>%
summarize(count = n()) %>%
mutate(percent = count/sum(count))
ggplot(data = df1, aes(x = Species, y = count, label = paste0(round(percent,2),"%"))) +
geom_bar(stat="identity") +
geom_text(aes(y = count*1.1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.