我有一个数据集,例如
outcome <- c(rnorm(500, 45, 10), rnorm(250, 40, 12), rnorm(150, 38, 7), rnorm(1000, 35, 10), rnorm(100, 30, 7))
group <- c(rep("A", 500), rep("B", 250), rep("C", 150), rep("D", 1000), rep("E", 100))
reprex <- data.frame(outcome, group)
我可以将其绘制为“炸药”图:
graph <- ggplot(reprex, aes(x=group, y=outcome, fill=..y..)) +
stat_summary(geom = "bar", fun.y = mean) +
stat_summary(geom = "errorbar", fun.data = mean_cl_normal, width = 0.1)
给予:
我还想在每列下方添加一个标签,指定该组中有多少观察值。但是我不知道如何做到这一点。我试过:
graph + geom_label (aes(label=paste(..count.., "Obs.", sep=" ")), y=-0.75, size=3.5, color="black", fontface="bold")
返回
Error in paste(count, "Obs.", sep = " ") :
cannot coerce type 'closure' to vector of type 'character'
我也试过
graph + stat_summary(aes(label=paste(..y.., "Obs.", sep=" ")), fun.y=count, geom="label")
但这会返回:
Error: stat_summary requires the following missing aesthetics: y
我知道如果我先制作一个汇总统计数据框,我可以做到这一点,但这将导致我每次需要图表时都创建一个新数据框,因此我希望能够使用 stat_summary() 绘制它来自原始数据集。
有谁知道如何做到这一点?
最佳答案
无需创建新的数据框,您可以使用 dplyr
获取计数。并计算它(“即时”)如下:
library(dplyr)
library(ggplot2)
ggplot(reprex, aes(x=group, y=outcome, fill=..y..)) +
stat_summary(geom = "bar", fun.y = mean) +
stat_summary(geom = "errorbar", fun.data = mean_cl_normal, width = 0.1)+
geom_label(inherit.aes = FALSE, data = . %>% group_by(group) %>% count(),
aes(label = paste0(n, " Obs."), x = group), y = -0.5)
关于r - 如何将带有观察计数的标签添加到 stat_summary ggplot?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60040581/