Question

I have a boxplot and would like to add simple horizontal lines with geom_hline for each boxplot individually.

I've tried on a boxplot example from R. The problems are that:

  • The lines span the whole plot instead of just the boxplot.
  • They are behind the boxplots.. ;-)

Thanks for any help in advance.

    ### ADDING Lines
    somelines <- data.frame(value=c(0.2,0.3,0.4,0.6,0.7),boxplot.nr=c(1,2,3,4,5))

    abc <- adply(matrix(rnorm(100), ncol = 5), 2, quantile, c(0, .25, .5, .75, 1))
    b <- ggplot(abc, aes(x = X1, ymin = `0%`, lower = `25%`, middle = `50%`, upper = `75%`, ymax = `100%`)) + 
        geom_hline(aes(yintercept= value),somelines)
    b + geom_boxplot(stat = "identity") 
    b + geom_boxplot(stat = "identity") + coord_flip()
    b + geom_boxplot(aes(fill = X1), stat = "identity")

my try

Was it helpful?

Solution

You can use geom_segment() to add those lines. Use boxplot.nr-0.5 for start of lines and boxplot.nr+0.5 for the end of lines and value for y and yend. Also add inherit.aes=FALSE inside geom_segment() to ensure that geom_segment() doesn't look for the variable X1 that you use for the fill for boxplot.

ggplot(abc, aes(x = X1, ymin = `0%`, lower = `25%`, middle = `50%`, 
                                   upper = `75%`, ymax = `100%`)) + 
  geom_boxplot(aes(fill = X1), stat = "identity")+
  geom_segment(data=somelines,aes(x=boxplot.nr-0.5,xend=boxplot.nr+0.5,
                       y=value,yend=value),inherit.aes=FALSE,color="orange",size=1.5)

The same result can be atchieved also with second call to geom_boxplot() - as there is only one value in each level for somelines object, then boxplots will appear as lines.

ggplot(abc, aes(x = X1, ymin = `0%`, lower = `25%`, middle = `50%`, 
                upper = `75%`, ymax = `100%`)) + 
  geom_boxplot(aes(fill = X1), stat = "identity")+  
  geom_boxplot(data=somelines,aes(factor(boxplot.nr),value),
               inherit.aes=FALSE,color="orange",size=1.5)

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top