5

I would like to change the point denoting the mean in ggerrorplot to a horizontal line (similar to the line used to denote a median in a boxplot). I would like this line to be slightly thicker than the error bars.

I do not see an option to do so in the ggerrorplot documentation. Will I need to do some hacking and perhaps overlay a line outside of ggerrorplot?

plot

# 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")
M--
  • 25,431
  • 8
  • 61
  • 93

2 Answers2

2

My hacky solution is getting the mean from ggplot_build object and then use geom_line to add your desired line to the plot:

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) 

Created on 2019-06-11 by the reprex package (v0.3.0)

M--
  • 25,431
  • 8
  • 61
  • 93
2

Add a point layer with argument shape = 95 as shown by @hrbrmstr here: https://stackoverflow.com/a/39601572/8583393

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")

enter image description here

I removed the pointrange layer which does not seem to be needed when you add the horizontal lines / bars.


In case you need control of the width of the horizontal lines, here is an option that uses geom_segment.

We calculate the y-axis values first

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

Then plot

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
  )

enter image description here

markus
  • 25,843
  • 5
  • 39
  • 58
  • Do we have control over length of the line? – M-- Jun 11 '19 at 21:17
  • @M-M I guess not with the point layer as mentioned in the linked post (but I found it looked quite good this way). Will add a second option that uses `geom_segment` for completeness. – markus Jun 11 '19 at 21:19