按组划分的 Ggplot 箱线图,显示更改摘要统计信息

Ggplot boxplot by group, change summary statistics shown

我想更改以下箱线图中显示的汇总统计数据:

我创建了如下箱线图:

ggplot(as.data.frame(beta2), aes(y=var1,x=as.factor(Year))) + 
  geom_boxplot(outlier.shape = NA)+
  ylab(expression(beta[1]))+
  xlab("\nYear")+
  theme_bw()

框的默认值是第一和第三分位数。我希望该框显示 2.5% 和 97.5% 的分位数。我知道可以通过将以下内容添加到 geom_boxplot:

来轻松更改一个箱线图可视化时显示的内容
aes(
    ymin= min(var1),
    lower = quantile(var1,0.025),
    middle = mean(var1),
    upper = quantile(var1,0.975),
    ymax=max(var1))

但是,这不适用于按组生成箱线图的情况。知道怎么做吗?您可以使用 Iris 数据集:

ggplot(iris, aes(y=Sepal.Length,x=Species)) + 
  geom_boxplot(outlier.shape = NA)

编辑:

接受的答案确实有效。我的数据框非常大,因此提供的方法需要一些时间。我在这里找到了另一个解决方案:SOLUTION 适用于大型数据集和我的特定需求。

这可以通过 stat_summary 通过设置 geom="boxplot" 来实现。并传递给 fun.data 一个函数,该函数 returns 一个数据框,其中包含您要在箱线图中显示为 yminlower、...的汇总统计数据:

library(ggplot2)

ggplot(iris, aes(x = Species, y = Sepal.Length)) +
  stat_summary(geom = "boxplot", fun.data = function(x) {
    data.frame(
      ymin = min(x),
      lower = quantile(x, 0.025),
      middle = mean(x),
      upper = quantile(x, 0.975),
      ymax = max(x) 
    )}, outlier.shape = NA)