r - 带有计数的堆叠条形图中 geom_text 的百分比

标签 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

最佳答案

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

关于r - 带有计数的堆叠条形图中 geom_text 的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59444265/

相关文章:

r - 使用 rSymPy 计算泰勒级数

r - ggplot2:创建有序组条形图 - (使用重新排序)

r - 在 ggplot2 r 中操作 geom_bar 和 coord_polar 的描绘

r - Windows 中的 PDF 展平

r - 如何在 ggplot2 中旋转标签?

r - 如何使用 geom_bar() 在 R 中创建两个分组列

r - 如何在绘图中使用 geom_line 添加连续线

R - 将一列数据帧拆分为多列

r - 如何在 mutate 函数的计算中使用变量?

r - ggplot2:添加线和点显示手段(stat_summary)