我想要一个堆叠条形图,其中包含基于计数的百分比。
我几乎达到了我想要的,但文本中的每个值都是 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()
建立在这个答案 https://stackoverflow.com/a/49566235/1842673
你可以使用这个:
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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)