R: 在 geom_bar(position = 'fill') 中显示值

R: show values in geom_bar(position = 'fill')

我有以下假数据:

n <- 100

set.seed(1)
df <- data.frame(grp = sample(c("A", "B", "C"), size = n, replace = TRUE),
                 values = sample(1:10, n, replace = TRUE) )

df

我的目标是得到一个如下所示的“填充”条形图,但我不知道如何使用 geom_text() 来为条形的每个部分添加百分比值。

ggplot(df, aes(x = values, fill = grp)) +
  geom_bar(position = 'fill') +
  geom_text(??)

有人能帮帮我吗?

您在找这样的东西吗?

df2 <- as.data.frame(apply(table(df), 2, function(x) x/sum(x)))
df2$grp <- rownames(df2)
df2 <- reshape2::melt(df2)

ggplot(df2, aes(x = variable, y = value, fill = grp)) +
  geom_col(position = "fill") +
  geom_text(aes(label = ifelse(value == 0, "", scales::percent(value))),
            position = position_fill(vjust = 0.5)) +
  scale_y_continuous(labels = scales::percent, name = "Percent") +
  labs(x = "Value")