Search code examples
rggplot2facetfacet-grid

Add a line to each facet in a grid


Suppose I have the following dataframe:

  dates          types vals
1 2018-02-01     a     10
2 2018-03-01     a     11
3 2018-04-01     a     12
4 2018-05-01     b     20
5 2018-06-01     b     21
6 2018-07-01     b     22
7 2018-08-01     c     30
8 2018-09-01     c     31
9 2018-10-01     c     32

I've visualized it as a grid with 3 facets (one for each type: a, b, and c), with a common X-axis (the dates):

gg <- ggplot(df, aes(x = dates, y = vals)) + 
  geom_line(aes(color = df$types)) +
  geom_point() +
  facet_grid(types ~ ., scales = "free_y") +
  scale_color_manual(values =c("blue", "orange", "green"))

enter image description here

Now I'd like to add a horizontal line for each facet, such that each facet will have its own y-intercept. Based on similar questions, I've tried to create a dataframe with a column of intercepts:

lower = seq(10,30,10); upper = seq(12,32,10)
bounds <- data.frame(lower, upper)

And add it using geom_hline:

gg + geom_hline(aes(yintercept = lower), data = bounds, color = 'red')

But the result is having each facet all three lines, instead of its own row (I also want to add a line with the upper column, but I guess the solution is symmetric).

enter image description here


Solution

  • You need to add the lower specification to match the faceted data like so:

    library('dplyr')
    df <- df %>% mutate(lower = rep(c(10,20,30), each =3))
    df
           dates types vals lower
    1 2018-02-01     a   10    10
    2 2018-03-01     a   11    10
    3 2018-04-01     a   12    10
    4 2018-05-01     b   20    20
    5 2018-06-01     b   21    20
    6 2018-07-01     b   22    20
    7 2018-08-01     c   30    30
    8 2018-09-01     c   31    30
    9 2018-10-01     c   32    30
    

    Then specify the plot as before and add the geom_hline like so on the altered df with lower column - like so:

    gg + geom_hline(aes(yintercept = lower), color = 'red')
    

    Then you get something like this:

    enter image description here