On a generic plot, with time on the x-axis, I would like to highlight a period of some specific years.
How can I bestly do this? My idea is for example a light yello
Here is a solution that uses zoo simply because that makes the subsetting easy. You could do the same with standard indexing as well:
## create a long monthly sequence and a sub-sequence
months <- seq( as.Date("1950-01-01"), as.Date("2009-12-12"), by="month")
subset <- seq( as.Date("1970-01-01"), as.Date("1979-12-31"), by="month")
## generate some random values
set.seed(42)
values <- cumsum(rnorm(length(months)))
## plot as a zoo object, overlay a gray background and overplot a line in red
library(zoo)
Z <- zoo(values, months)
plot(Z)
rect(xleft=head(subset,1), xright=tail(subset,1),
ybottom=par("usr")[3], ytop=par("usr")[4],
density=NA, col="lightgray")
lines(Z[subset], col='red')
box()
(source: eddelbuettel.com)
By using par("usr")
we avoid the need for explicit values for upper and lower region marks. And the zoo
indexing makes finding the start- and endpoints easy. This would work the same way for data in different time resolutions.