Skip to content

Instantly share code, notes, and snippets.

@emanuelhuber
Created February 11, 2021 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emanuelhuber/5c770069fec5dfd6aa82a4537cb6236e to your computer and use it in GitHub Desktop.
Save emanuelhuber/5c770069fec5dfd6aa82a4537cb6236e to your computer and use it in GitHub Desktop.
Add colored rectangle as background to a xts time-series (R language)
addPolySeq <- function(tval, y, ylim, ...){
i <- seq(1, by = 2, to = length(tval)- 1)
tval_p <- cbind(tval[i], tval[i + 1])
u <- (apply(tval_p, 1, FUN, y = y, ylim = ylim, ...))
u
}
FUN <- function(x, y, ylim, ...){
ynew <- y[paste0(c(as.Date(x[1]), as.Date(x[2])), collapse = "/")]
nr <- nrow(ynew)
if(nr > 0){
shade <- cbind(upper = rep(ylim[2], nr), lower = rep(ylim[1], nr))
shade <- xts(shade, index(ynew))
addPolygon(shade, ...)
}
}
plot(ps)
tval <- seq(as.Date("2014-02-01"), length=35, by="quarters")
addPolySeq(tval, y = ps, ylim = c(0, 100), on = -1, col = "dodgerblue")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment