screechOwl
screechOwl

Reputation: 28159

R set plot background based on date

I have a chart of financial activity and a couple running sums.enter image description here Things are getting a little busy and I'm having trouble distinguishing fiscal (ends June 30th) vs calendar year. Is there a way to set the background to different colors based on date?

In other words could I set background to lite green where 2009-06-30 < date < 2010-07-01?

Upvotes: 3

Views: 1302

Answers (3)

Geek On Acid
Geek On Acid

Reputation: 6410

Apply a piece of both suggestions by @G-Grothendieck and @vincent - use rect within zoo package. zoo is excellent for any visualization of time series.

library(zoo)
#random data combined with time series that starts in 2009-01
v <- zooreg(rnorm(37), start = as.yearmon("2009-1"), freq=12)
plot(v, type = "n",xlab="",xaxt="n")
#this will catch some min and max values for y-axis points in rect
u <- par("usr")
#plot green rect - notice that x-coordinates are defined by date points
rect(as.yearmon("2009-6-30"), u[3], as.yearmon("2010-7-1"), u[4], 
        border = 0, col = "lightgreen")
lines(v)
axis(1, floor(time(v)))
#customized x-axis labels based on dates values
axis(1,at=c(2009.4, 2010.5),padj=-2,lty=0,labels=c("start","end"),cex.axis=0.8)

enter image description here

Upvotes: 5

G. Grothendieck
G. Grothendieck

Reputation: 269654

Check out xblocks.zoo in the zoo package. e.g., example(xblocks.zoo)

Upvotes: 5

Vincent Zoonekynd
Vincent Zoonekynd

Reputation: 32351

You can plot grey rectangles, with rect, before plotting the curves. You will also need the dimensions of the plotting area: they are in par("usr").

library(quantmod)
getSymbols("A")
plot( index(A), coredata(Ad(A)), type="n" )
# This example uses calendar years: adapt as needed
dates <- c( 
  ISOdate( year(min(index(A))),     1, 1 ),
  ISOdate( year(max(index(A))) + 1, 1, 1 )
)
dates <- as.Date(dates)
dates <- seq.Date(dates[1], dates[2], by="2 year")
rect( 
  dates, 
  par("usr")[3], 
  as.Date( ISOdate( year(dates) + 1, 1, 1 ) ),
  par("usr")[4], 
  col="grey",
  border=NA
)
lines(index(A), coredata(Ad(A)), lwd=3)

Upvotes: 2

Related Questions