在ggplot R中根据年份更改背景颜色面板 [英] Change background color panel based on year in ggplot R

查看:13
本文介绍了在ggplot R中根据年份更改背景颜色面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm plotting a time series for three different years 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 中绘制收盘价,以便每年在图上都有不同的背景色图块?

How do I plot the closing price in ggplot such that each year has different background color tiles on the plot?

推荐答案

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

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

此解决方案中使用了一些帖子:geom_rect 和 alpha使用 geom_rect 添加衰退.

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

这篇关于在ggplot R中根据年份更改背景颜色面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆