Search code examples
rggplot2time-seriesdummy-variable

ggplot2: Mark years with geom_ribbon


I have a dataset that looks like this:

library(tidyverse)

df  <- tribble(
  ~year, ~value, ~dummy,
  #--|--|----
  2003, 3, 0,
  2004, 4, 0,
  2005, 7, 1,
  2006, 9, 1,
  2007, 15, 1,
  2008, 17, 0,
  2009, 7, 0,
  2010, 8, 0,
  2011, 8, 0,
  2012, 7, 0,
  2013, 2, 0,
  2014, 9, 1,
  2015, 5, 0
)

I'm trying to plot the value series and have gray bars in the background for years that are marked with dummy == 1. (Like this)

I have trouble passing the right years to R. I've tried the following, but it doesn't work:

dummy_years <- df$year[df$dummy == 1]

ggplot(df , aes(x = year)) +
  geom_ribbon(aes(x = dummy_years, ymin = -Inf, ymax = Inf)) +
  geom_line(aes(y = value))

I get: Error: Aesthetics must be either length 1 or the same as the data (13): x, ymin, ymax.


Solution

  • We can use geom_rect, filling by dummy, and using a scale_fill_manual:

    library(ggplot2)
    ggplot(df) +
        geom_line(aes(year, value)) +
        geom_rect(aes(ymax = Inf, 
                      ymin = -Inf, 
                      xmin = year, 
                      xmax = year + 1, 
                      fill = factor(dummy)), 
                  alpha = .5, 
                  show.legend = FALSE) +
        scale_fill_manual(values = c('transparent', 'grey45')) +
        theme_minimal()