带计数的堆叠式barplot中geom_text的百分比

时间:2019-12-22 12:38:33

标签: r ggplot2 geom-bar geom-text

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

enter image description here

1 个答案:

答案 0 :(得分:2)

基于this answer

您可以使用此:

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()

enter image description here