5

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

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

Richard Telford
  • 9,558
  • 6
  • 38
  • 51
Rhodo
  • 1,234
  • 4
  • 19
  • 35
  • Is there a reason for separating the backgrounds by color? Why not color code the line plot itself? – Bahae Omid Oct 25 '15 at 01:50
  • I could also use: `p + geom_vline(xintercept=as.numeric(c(df$date[50],df$date[75],df$date[100]))` to put vertical lines where I want them but I'd like to figure it out as another option – Rhodo Oct 25 '15 at 15:59

1 Answers1

5

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

enter image description here

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

Community
  • 1
  • 1
bouncyball
  • 10,631
  • 19
  • 31