This question builds on How can i provide shades between dates on x axis in R plot? and How to align multiple ggplot2 plots and add shadows over all of them.
Before I go into details, I want to be able to condense the amount of code I would have to write in order to shade many different sections. I hope to be able to put all of this information into one piece of code.
Here is my MWE:
library(ggplot2)
library(scales)
set.seed(1)
data <- data.frame(Date = seq(as.Date('2000-01-01'),
len= 23, by="1 day"),
Value = sample(1:50, 23, replace=TRUE))
rect1 <- data.frame(xmin=as.Date('2000-01-03 12:00:00'),
xmax=as.Date('2000-01-04 12:00:00'),
ymin=-Inf,
ymax=Inf)
rect2 <- data.frame(xmin=as.Date('2000-01-10'),
xmax=as.Date('2000-01-11'),
ymin=-Inf,
ymax=Inf)
rect3 <- data.frame(xmin=as.Date('2000-01-17 00:00:00'),
xmax=as.Date('2000-01-18 00:00:00'),
ymin=-Inf,
ymax=Inf)
ggplot() +
geom_line(data=data, aes(x = Date, y = Value)) +
geom_rect(data = rect1, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), alpha = 0.4) +
geom_rect(data = rect2, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), alpha = 0.4) +
geom_rect(data = rect3, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), alpha = 0.4) +
scale_x_date(breaks = date_breaks("1 day"), labels = date_format("%d"))
Thus, I get a plot with 3 different shaded regions:
Having 3 sections to shade isn't too bad, but what if I needed to shade 100? Is there a way to not define 100 data frames and then add all these shadings one-by-one?
And secondly, I want to have my shadings be over the middle of the value. But in all three specifications (rect1
, rect2
, and rect3
), each shading starts at the value for that date and ends at the value for the next date. Any tips on how to do this?