如何将带有观察计数的标签添加到 stat_summary ggplot?

Mel*_*Mel 5 r summary ggplot2

我有一个数据集例如

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)
Run Code Online (Sandbox Code Playgroud)

我可以将其绘制为“炸药”图:

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)
Run Code Online (Sandbox Code Playgroud)

给予:

图表的图片

我还想在每列下方添加一个标签,指定该组中有多少个观察值。但是我不知道如何做到这一点。我试过:

graph + geom_label (aes(label=paste(..count.., "Obs.", sep=" ")), y=-0.75, size=3.5, color="black", fontface="bold")
Run Code Online (Sandbox Code Playgroud)

返回

Error in paste(count, "Obs.", sep = " ") : 
  cannot coerce type 'closure' to vector of type 'character'
Run Code Online (Sandbox Code Playgroud)

我也尝试过

  graph + stat_summary(aes(label=paste(..y.., "Obs.", sep=" ")), fun.y=count, geom="label")
Run Code Online (Sandbox Code Playgroud)

但这会返回:

Error: stat_summary requires the following missing aesthetics: y
Run Code Online (Sandbox Code Playgroud)

我知道如果我首先制作一个汇总统计数据框,那么我可以做到这一点,但这将导致我每次需要图表时创建一个新的数据框,因此我理想地希望能够使用 stat_summary() 绘制它来自原始数据集。

有谁知道如何做到这一点?

dc3*_*c37 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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Stu*_*olf 2

当已经声明了 ay 变量时,您不能使用 stat="count" 。我想说最简单的方法是为计数创建一个小数据框:

label_df = reprex %>% group_by(group) %>% summarise(outcome=mean(outcome),n=n())
Run Code Online (Sandbox Code Playgroud)

然后用它来绘制

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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述