【问题标题】:How do I plot the mean instead of the median with geom_boxplot? [duplicate]如何使用 geom_boxplot 绘制平均值而不是中值? [复制]
【发布时间】:2018-05-01 06:05:07
【问题描述】:

出于某种愚蠢的原因,我需要创建一个箱线图,其中中线是 mean 而不是中位数。我已经检查了 stackoverflow 并找到了 adding 平均线的示例,但不完全是我需要的。我尝试使用 stat_smooth 但没有骰子。有什么想法吗?

代码如下:

dust <- c(4.5, 3.7, 5, 5.2, 8.5, 6.6, 4.7, 5, 5.7, 4.3, 2.3, 7.6, 5.2, 
          6, 8.7, 7.5, 7.7, 11, 9, 6.5, 8.7, 5, 2.2, 7.5, 7.5, 3.5)

wind <- c("Present", "Absent", "Absent", "Absent", "Absent", "Absent", 
  "Absent", "Absent", "Absent", "Present", "Absent", "Absent", 
  "Present", "Present", "Absent", "Absent", "Absent", "Absent", 
  "Absent", "Present", "Absent", "Present", "Absent", "Absent", 
  "Absent", "Present")

df <- data.frame(dust,wind)

plot <- ggplot(data=df,aes(x=wind,y=dust))+geom_boxplot()+stat_smooth()

plot

【问题讨论】:

  • geom_boxplot 可以采用更详细的参数,如中间(即平均值)、ymin、lower 等。查看 ?geom_boxplot
  • geom_boxplot(middle = mean(dust))。另外,为什么stat_smooth?它有什么作用?
  • @RuiBarradas 不要忘记aesgeom_boxplot(aes(middle = mean(dust)))
  • @neilfws 是的,谢谢。对不起,我误导了OP。
  • @Chris 到目前为止有两个支持,这似乎是一个值得未来用户参考的问题。你不会发表你的评论作为答案吗?

标签: r ggplot2


【解决方案1】:

有几种方法可以做到这一点:

1。使用中间

最简单的就是调用:

plot <- ggplot(data = df, aes(y = dust, x = wind)) + 
        geom_boxplot(aes(middle = mean(dust))

2。使用 fatten = NULL

您还可以利用geom_boxplot() 中的fatten 参数。这控制了中线的粗细。如果我们将其设置为NULL,则它不会绘制中线,我们可以使用stat_summary 插入一条均值线。

plot <- ggplot(data = df, aes(y = dust, x = wind)) + 
  geom_boxplot(fatten = NULL) +
  stat_summary(fun.y = mean, geom = "errorbar", aes(ymax = ..y.., ymin = ..y..),
               width = 0.75, size = 1, linetype = "solid")
print(plot)

使用fatten = NULL输出

如您所见,上述方法绘制得很好,但是当您评估代码时,它会输出一些警告消息,因为实际上并不期望 fatten 采用 NULL 值。

好处是这种方法可能更灵活一些,因为我们本质上是“擦除”中线并添加我们想要的任何内容。例如,我们也可以选择保留中位数,并将均值添加为虚线。

【讨论】:

    【解决方案2】:
    ggplot(df) + 
      geom_boxplot(
        aes(
          x = wind, ymin = min(dust), lower = quantile(dust, .25), 
          middle = mean(dust), upper = quantile(dust, .75),
          ymax = max(dust)
        ), stat = "identity"
      )
    

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 1970-01-01
      • 2019-05-11
      • 2017-08-30
      • 1970-01-01
      • 1970-01-01
      • 2017-04-25
      • 2015-04-05
      • 2020-03-07
      相关资源
      最近更新 更多