将 ggerorplot 中表示均值的点更改为一条线

Change point denoting mean in ggerrorplot to a line

我想将 ggerrorplot 中表示平均值的点更改为水平线(类似于用于表示箱线图中中位数的线)。我希望这条线比误差线稍粗。

我在 ggerrorplot 文档中没有看到这样做的选项。我是否需要进行一些黑客攻击并可能在 ggerrorplot 之外覆盖一条线?

# ToothGrowth data set available in R datasets
df <- ToothGrowth

# Examine first 10 rows
head(df, 10)
# len supp dose
# 1   4.2   VC  0.5
# 2  11.5   VC  0.5
# 3   7.3   VC  0.5
# 4   5.8   VC  0.5
# 5   6.4   VC  0.5
# 6  10.0   VC  0.5
# 7  11.2   VC  0.5
# 8  11.2   VC  0.5
# 9   5.2   VC  0.5
# 10  7.0   VC  0.5

require(ggpubr)

# Add mean, jitter points and error bars
ggerrorplot(df, x = "dose", y = "len",
            add = c("mean","jitter"), error.plot= "errorbar")

我的 hacky 解决方案是从 ggplot_build 对象获取 mean,然后使用 geom_line 将您想要的行添加到图中:

df <- ToothGrowth

require(ggplot2)
require(ggpubr)

g <- ggerrorplot(df, x = "dose", y = "len",
                     add = "jitter", error.plot= "errorbar")

gb <- ggplot_build(g)

g + geom_line(data=data.frame(xavg=c(t(gb$data[[2]][,c("xmin","xmax")])),
                              yavg=rep(gb$data[[2]]$y, each=2),
                              grps=rep(row.names(gb$data[[2]]),each=2)),
              aes(x = xavg, y = yavg, group=grps), size=1) 

reprex package (v0.3.0)

于 2019-06-11 创建

添加带参数 shape = 95 的点层,如 @hrbrmstr 所示:

p <- ggerrorplot(df, x = "dose", y = "len", 
            add = "jitter", # 'mean' and c() removed in this line
            error.plot = "errorbar")

p + stat_summary(
    geom = "point",
    shape = 95,
    size = 30,
    col = "red",
    fun.y = "mean")

我删除了添加水平线/条时似乎不需要的点范围层。


如果您需要控制水平线的宽度,这里有一个使用 geom_segment.

的选项

我们先计算 y-axis 个值

df_segment <- aggregate(len ~ dose, p$data, FUN = mean)

然后剧情

p +
  geom_segment(
    data = transform(df_segment, dose = as.numeric(dose)),
    aes(
      x = dose - 0.1,
      xend = dose + 0.1,
      y = len,
      yend = len
    ),
    col = "red",
    size = 1
  )