Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Provide shades between dates on x axis [duplicate]

Tags:

r

ggplot2

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

like image 374
2sb Avatar asked May 10 '12 21:05

2sb


2 Answers

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, m

like image 63
Eric Fail Avatar answered Sep 16 '22 18:09

Eric Fail


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.

like image 29
Brian Diggs Avatar answered Sep 17 '22 18:09

Brian Diggs