如何在 stat_summary ggplot 中添加带有观测计数的标签?

5

我有一个数据集,例如:

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()绘制图形。

有人知道怎么做吗?


graph + geom_label(aes(label=stat(y), group = group), stat = "summary", fun.y = mean) 将数值放置在条形图的顶部,但这只是一个开始。 - Bas
2个回答

5

使用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)

enter image description here


2
当已经声明了y变量时,无法使用stat="count"。我建议最简单的方法是创建一个用于计数的小数据框:
label_df = reprex %>% group_by(group) %>% summarise(outcome=mean(outcome),n=n())

然后使用该图绘制。
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_text(data=label_df,aes(label=paste(n, "Obs.", sep=" ")), size=3.5, color="black", fontface="bold",nudge_y =1)

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接