使用geom_text在层叠条形图中显示百分比和计数

5
我想要一个堆积条形图,并且在上面显示百分比,基于计数得到。我已经接近达到我的目标,但是文本中的每个值都是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


不行,因为我不能使用 stat = "identity"。但是谢谢! - TobiSonne
1个回答

9

基于 这个答案

你可以使用以下方式:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接