Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R set plot background based on date

Tags:

date

plot

r

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?

like image 335
screechOwl Avatar asked Sep 05 '26 04:09

screechOwl


2 Answers

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

like image 95
Geek On Acid Avatar answered Sep 07 '26 19:09

Geek On Acid


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

like image 33
G. Grothendieck Avatar answered Sep 07 '26 17:09

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!