我想创建一个堆积的条形图,其中包含基于计数的百分比。 我几乎达到了我想要的水平,但是文本中的每个值都是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()
答案 0 :(得分:2)
您可以使用此:
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()