I have a dataframe with with a value measured with an instrument at four locations over consecutive time periods. I wish to have the night time (6pm to 6am) shaded grey to help with interpretation. The code below plots this correctly except i also want to use facet_grid(..., scales = 'free_x') to drop the unwanted time periods when the instrument was not collecting data at each location.
require(ggplot2)
df.long <- data.frame(Timestamp = seq.POSIXt(as.POSIXct("2018-07-05 18:00:00", format = '%Y-%m-%d %H:%M:%S'), by = 'hour', length.out = 192),
Location = c(rep('A', 48), rep('B', 48), rep('C', 48), rep('D', 48)),
value = sin(seq(1:192)/4))
shade <- data.frame(dusk = seq.POSIXt(as.POSIXct("2018-07-05 18:00:00", format = '%Y-%m-%d %H:%M:%S'), by = 'day', length.out = 8),
dawn = seq.POSIXt(as.POSIXct("2018-07-06 06:00:00", format = '%Y-%m-%d %H:%M:%S'), by = 'day', length.out = 8),
top = Inf,
bottom = -Inf)
ggplot(df.long) +
geom_rect(data = shade,
aes(xmin = dusk, xmax = dawn,ymin = bottom, ymax = top),
fill = 'light grey', alpha = 0.5) +
geom_line(aes(x = Timestamp, y = value, col = Location)) +
geom_point(aes(x = Timestamp, y = value, fill = Location), pch = 21) +
facet_grid( ~ Location, scales = 'free_x') +
ylab('Flux (mg O2 m-2 h-1)') +
theme_bw()
The X axis is scaled correctly with facet_grid(..., scales = 'free_x') when I exclude the call for geom_rect. How do i go about plotting the shaded geom_rect on the second plot without the X-axis scales expanding?
ggplot(df.long) +
# geom_rect(data = shade, aes(xmin = dusk, xmax = dawn,
# ymin = bottom, ymax = top), fill = 'light grey', alpha = 0.5) +
geom_line(aes(x = Timestamp, y = value, col = Location)) +
geom_point(aes(x = Timestamp, y = value, fill = Location), pch = 21) +
facet_grid( ~ Location, scales = 'free_x') +
ylab('Flux (mg O2 m-2 h-1)') +
theme_bw() +
theme(legend.position = 'none')
I have also tried substituting geom_rect with:
annotate("rect",
xmin = shade$dusk, xmax = shade$dawn, ymin = shade$bottom, ymax = shade$top,
fill = "light grey", alpha = 0.5) +


