ggplot2:用geom_ribbon标记年份

时间:2017-07-10 14:36:25

标签: r ggplot2 time-series dummy-variable

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

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

1 个答案:

答案 0 :(得分:1)

我们可以使用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()