Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot2: Add means as horizontal line in a boxplot

Tags:

r

ggplot2

boxplot

I have created a boxplot using ggplot2:

library(ggplot2)

dat <- data.frame(study = c(rep('a',50),rep('b',50)), 
                  FPKM = c(rnorm(1:50),rnorm(1:50)))

ggplot(dat, aes(x = study, y = FPKM)) + geom_boxplot()

The boxplot shows the median as a horizontal line across each box.

enter image description here

How do I add a dashed line to the box representing the mean of that group?

Thanks!

like image 736
Komal Rathi Avatar asked Oct 19 '16 15:10

Komal Rathi


1 Answers

You can add horizontal lines to plots by using stat_summary with geom_errorbar. The line is horizontal because the y minimum and maximum are set to be the same as y.

ggplot(dat, aes(x = study, y = FPKM)) + 
    geom_boxplot() +
    stat_summary(fun.y = mean, geom = "errorbar", aes(ymax = ..y.., ymin = ..y..),
                 width = .75, linetype = "dashed")

enter image description here

like image 110
aosmith Avatar answered Sep 30 '22 00:09

aosmith