【问题标题】:Percentages for geom_text in stacked barplot with counts带有计数的堆叠条形图中 geom_text 的百分比
【发布时间】:2019-12-22 12:38:33
【问题描述】:

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

【问题讨论】:

标签: r ggplot2 geom-bar geom-text


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 2020-04-18
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 2013-05-18
    • 2021-07-01
    相关资源
    最近更新 更多