Shade indicator variables R

129 views Asked by At

please help: I want to shade a time-series figure in R's plot for all values where an indicator variable, z == 1.

Here follows a code which generates a similar scenario that I am looking at:

x <-runif(100, 5.0, 7.5)
y <-runif(100, 1, 10)
z = as.numeric(y >= 5)
date = seq(as.Date("1910/1/1"), as.Date("2009/1/1"), "years")
data = data.frame(cbind(x,y,z))
color <- rgb(190, 190, 190, alpha=80, maxColorValue=255)
plot(date,x, type='l')
rect(xleft=date[10], xright=date[40], ybottom=5, ytop=7.5, col = color,density=100)

From the code, I can only specify dates one by one. But suppose I want to shade all the areas where z==1? I.e. all the dates where z == 1. Any ideas how this could be done?

Manythanks, Nic

1

There are 1 answers

0
Stephan Kolassa On BEST ANSWER

Just feed an entire vector of dates into the xleft and xright parameters, as indexed by z==1. Don't do line shading, it will run a long time, just change the color to grey. Afterwards, plot the time series again over the rectangles:

plot(date,x, type='l')
rect(xleft=date[z==1]-180,xright=date[z==1]+180,
  ybottom=5, ytop=7.5, col="grey",border=NA)
lines(date,x)

rectangle