Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic background in plot() based on x-axis values?

Tags:

plot

r

I'm looking to implement EXACTLY this, but using plot() instead of ggplot2. There is even a reply on the blog by someone saying they did this with plot, but the link to their code is dead. I'm literally trying to do the exact same thing. I've downloaded data from FRED using quantmod's getSymbols(), and I have that data in a df, which I'm plotting with plot(). The x-axis are dates, and I want to change the background color based on a specific set of dates. Any ideas or hints how I can do this with plot?

Thank you!

like image 478
ch-pub Avatar asked Nov 16 '25 22:11

ch-pub


2 Answers

Based on this question: R: change background color of plot for specific area only (based on x-values)

## plotting area with no axes
plot(unrate.df, type = "n")
lim <- par("usr")
## adding one rectangle
for (i in 1:nrow(recessions.trim)) {
     rect(recessions.trim[i, 1], lim[3], 
          recessions.trim[i, 2], lim[4], border = "pink", col = "pink")
}
## adding the data
lines(unrate.df)
box()

enter image description here

like image 99
tonytonov Avatar answered Nov 19 '25 17:11

tonytonov


You can use this:

plot(unrate.df, type="n")
makeRectangles(recessions.trim, col="pink", alpha=0.5)
lines(unrate.df)
grid()

where the function makeRectangles is defined as:

makeRectangles = function(x, col, alpha=1, border=NA, ...) {

  col = col2rgb(col=col, alpha=FALSE)
  col = rgb(red=col[1], green=col[2], blue=col[3], 
              alpha=floor(255*alpha) , maxColorValue=255)
  rect(x[,1], par("usr")[3], x[,2], par("usr")[4], col=col, border=border, ...)

  return(invisible())
}

theplot

like image 27
Ricardo Oliveros-Ramos Avatar answered Nov 19 '25 17:11

Ricardo Oliveros-Ramos



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!