Change background color panel based on year in ggplot R

我的未来我决定 提交于 2019-12-06 01:24:00
bouncyball

We can use geom_rect for separating the backgrounds.

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

A few posts were used in this solution: geom_rect and alpha and using geom_rect to add recessions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!