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

Percentages for geom_text in stacked barplot with counts

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

基于

你可以使用这个:

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