ggplot2:堆叠条形图中的值标签 geom_bar(position = 'fill')

ggplot2: Value labels in stacked barplot with geom_bar(position = 'fill')

有人可以帮助我如何将值标签添加到 ggplot 中的堆叠条形图吗?有没有一种方法可以使用 geom_bar() 计算百分比,或者我必须手动计算百分比然后使用 geom_col()?

library(tidyverse)

df <- data.frame(var1 = sample(c("A","B"), size = 100, replace=TRUE),
                 var2 = sample(c("x", "y"), size=100, replace=TRUE))

df %>% 
  ggplot(aes(x = var1, fill = var2)) + 
    geom_bar(position = 'fill') +
    geom_text(aes(x = var1, fill = var2, label = "x")) <= ???

感谢您的帮助!

虽然 stat_count 会在幕后计算一些百分比(可以通过 ..prop..after_stat(prop) 访问,但大多数时候您必须手动计算百分比。因此更简单的方法可能是在将数据传递给 ggplot2 之前汇总数据。但是,我在下面的回答向您展示了一种使用 after_stattapply:

即时计算百分比的方法
library(tidyverse)

df <- data.frame(var1 = sample(c("A","B"), size = 100, replace=TRUE),
                 var2 = sample(c("x", "y"), size=100, replace=TRUE))

df %>% 
  ggplot(aes(x = var1, fill = var2)) + 
  geom_bar(position = 'fill') +
  geom_text(aes(x = var1, 
                label = scales::percent(after_stat(count / tapply(count, x, sum)[x])), 
                group = var2), position = "fill", stat = "count")