ggplot2:用 geom_ribbon 标记年份

ggplot2: Mark years with geom_ribbon

我有一个如下所示的数据集:

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
)

我正在尝试绘制 value 系列,背景中有灰色条,这些年标有 dummy == 1。 (喜欢this

我无法将正确的年份传递给 R。我尝试了以下方法,但它不起作用:

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))

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

我们可以使用geom_rect,填充dummy,然后使用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()