[英]Percentages for geom_text in stacked barplot with counts
I want to have a stacked barplot with percentages in it based on counts.我想要一个堆叠的条形图,其中包含基于计数的百分比。 I have almost reached what I want but every value in the text is 100% instead of the real percentage ... I think there is one small mistake in my code but I can not find it.我几乎达到了我想要的,但文本中的每个值都是 100% 而不是实际百分比......我认为我的代码中有一个小错误,但我找不到它。
ggplot(
mtcars,
aes(fill = factor(gear),
x = factor(carb))
) +
geom_bar(stat = "count",
position = "fill",
color = "black",
width = 0.5) +
geom_text(aes(label = scales::percent(..prop..)),
position = position_fill(vjust = 0.5),
stat = "count") +
coord_flip()
Building on this answer基于这个答案
You can use this:你可以使用这个:
ggplot(
mtcars,
aes(fill = factor(gear),
x = factor(carb))
) +
geom_bar(stat = "count",
position = "fill",
color = "black",
width = 0.5) +
geom_text(aes(label = scales::percent(..count../tapply(..count.., ..x.. ,sum)[..x..])),
position = position_fill(vjust = 0.5),
stat = "count") +
coord_flip()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.