Search code examples
rggplot2facet-grid

Add unique horizontal line for levels in facet_grid


I want to add a unique horizontal line across each row of a set of facet grid boxplots.

x<-c("species_X","species_X","species_X", "species_Y","species_Y",
     "species_Y", "species_Z", "species_Z", "species_Z") 
y<- c(1,2,3)


df<- data.frame(species= rep(x, 3),
                effort= rep(y, 9),
                value = rnorm(27, 3, 2))
 
ggplot(df, aes(x=value))+
  geom_boxplot()+
  facet_grid(species ~ effort, scales = "free_y")+
  coord_flip()+
  ylab("")

I would like to add the lines at the following values for each row:

add_lines<- c(4, 3, 4.7)

So 4 corresponds with species_X, 3 with species_Y, and 4.7 with species_Z. I've been able to add lines to all the boxplots, but only in a way where all the lines have the same value, or where all three lines are displayed on each boxplot like the following:

ggplot(df, aes(x=value))+
  geom_boxplot()+
  facet_grid(species ~ effort, scales = "free_y")+
  coord_flip()+
  ylab("")+
  geom_vline(xintercept = add_lines)

Any help with this would be greatly appreciated.


Solution

    1. coord_flip disturbs the direction of the line but changing to geom_vline will fix it.

    2. set species to unique and safe the numbers for lines in a dataframe.

    library(tidyverse)
    
    # data for lines
    add_lines = data.frame(species = unique(df$species),
                           hline = c(4,3,4.7)
                           )
    
    p <- ggplot(df, aes(x=value))+
      geom_boxplot()+
      facet_grid(species ~ effort, scales = "free_y")+
      coord_flip()+
      ylab("")
    
    p + 
      geom_vline(data = add_lines,
                 aes(xintercept = hline), color = "green")
    
    

    enter image description here