Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change point denoting mean in ggerrorplot to a line

Tags:

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")
like image 589
Mandy Avatar asked Jun 11 '19 20:06

Mandy


1 Answers

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

like image 174
markus Avatar answered Sep 20 '22 09:09

markus