I have a plot in R with date/time (POSIXct) on X axis and some data on Y axis.
I want to provide shade on x axis between say 3pm to 6PM of every date on x axis
Asked
Active
Viewed 1.1k times
7
-
in base graphics, probably using `?rect` (and possibly `par("usr")` to get the min/max y-value of the plot, in user units -- or `grconvertX/grconvertY`) to set up a bunch of shaded rectangles, then re-plot your data over them. A reproducible example would be nice. – Ben Bolker May 10 '12 at 21:40
2 Answers
23
More or less following what Brian Diggs suggests above,
#sample data
set.seed(666)
dat <- data.frame(x = seq(as.POSIXct('2011-03-27 00:00:00'),
len= (n=24), by="1 hour"), y = cumsum(rnorm(n)))
#Breaks for background rectangles
rects <- data.frame(xstart = as.POSIXct('2011-03-27 15:00:00'),
xend = as.POSIXct('2011-03-27 18:00:00'))
library(ggplot2)
ggplot() +
geom_rect(data = rects, aes(xmin = xstart, xmax = xend,
ymin = -Inf, ymax = Inf), alpha = 0.4) +
geom_line(data = dat, aes(x,y))
Would give you this,
8
Make a data.frame with columns that are 3 and 6 pm for each day covering the data. Use that for a geom_rect
layer (using Inf
and -Inf
for the y's). Put that layer before your data layers (so it is below them) and give the fill an alpha so the grid can be seen through it.
More detailed answer would be possible with a more detailed, reproducible question.

Brian Diggs
- 57,757
- 13
- 166
- 188