根据 ggplot R 中的年份更改背景颜色面板

Change background color panel based on year in ggplot R

我正在绘制 2013、2014、2015 三个不同年份的时间序列。

require(quantmod)
require(ggplot2)
getSymbols("AAPL", from='2013-01-1')
aapl.df = data.frame(date=time(AAPL), coredata(AAPL.Close))
ggplot(data=aapl.df, aes(x=date, y=AAPL.Close, group=1))+geom_line()

我如何在 ggplot 中绘制收盘价,以便每年在图上都有不同的背景颜色块?

我们可以使用geom_rect来分离背景。

ggplot()+
  geom_rect(aes(xmin = as.Date("2015-01-01"),
            xmax = as.Date("2015-12-31"),
                ymin = -Inf, ymax = Inf, fill = '2015'), alpha = .2)+
  geom_rect(aes(xmin = as.Date("2014-01-01"),
            xmax = as.Date("2014-12-31"),
                ymin = -Inf, ymax = Inf, fill = '2014'), alpha = .2)+
  geom_rect(aes(xmin = as.Date("2013-01-01"),
            xmax = as.Date("2013-12-31"),
                ymin = -Inf, ymax = Inf,fill = '2013'), alpha = .2)+
  geom_line(data=subset(aapl.df, date < '2016-01-01'),
            aes(x=date, y=AAPL.Close, group=1))+
  scale_fill_brewer(palette = 'Dark2', name = 'Year')+
  theme_bw()

此解决方案中使用了一些帖子:geom_rect and alpha and using geom_rect to add recessions