Rho*_*odo 5 r time-series ggplot2 quantmod
我正在绘制 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()
Run Code Online (Sandbox Code Playgroud)
如何在 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()
Run Code Online (Sandbox Code Playgroud)
此解决方案中使用了一些帖子:geom_rect 和 alpha以及使用 geom_rect 添加衰退。