【发布时间】:2017-08-04 08:41:57
【问题描述】:
我正在尝试通过geom_text() 在堆叠的 ggplot2 条形图中添加组百分比,计数在 y 轴上。我已经在这里看到并阅读了this question,但我认为它没有为我提供解决方案。
这是一个可重现的例子:
library(ggplot2)
library(scales)
df <- data.frame(Var1 = rep(c("A", "B", "C"), each = 3),
Var2 = rep(c("Gr1", "Gr2", "Gr3"), 3),
Freq = c(10, 15, 5, 5, 4, 3, 2, 10, 15))
ggplot(df) + aes(x = Var2, y = Freq, fill = Var1) +
geom_bar(stat = "identity") +
geom_text(aes(y = ..count.., label = scales::percent(..count../sum(..count..))),
stat = "count")
这是结果:
只是为了确保你明白我想要什么:我希望每个组 Gr1、Gr2、Gr3 在每个条形上方的百分比,总和为 100%。
基本上,这些是我这样做时得到的值:
prop.table(tapply(df$Freq, df$Var2, sum))
谢谢!
【问题讨论】: