Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i add shading to nighttime with geom_rect without facet scales expanding?

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()

enter image description here

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')

enter image description here

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) +
like image 256
Jordan Avatar asked Dec 02 '25 00:12

Jordan


1 Answers

One possible approach is to define only the relevant shading rectangles for each facet:

library(dplyr)

shade2 <- shade %>%
  # replicate shade for each facet
  slice(rep(seq(1, n()),
            times = n_distinct(df.long$Location))) %>%
  mutate(Location = rep(sort(unique(df.long$Location)),
                        each = n()/4)) %>%

  # calculate actual x-range associated with each facet, & join with shade
  left_join(df.long %>%
              group_by(Location) %>%
              summarise(xmin = min(Timestamp),
                        xmax = max(Timestamp)) %>%
              ungroup(),
            by = "Location") %>%

  # for each shade facet, keep only rows within relevant x-range
  filter(dusk >= xmin & dawn <= xmax)

ggplot(df.long) +
  geom_rect(data = shade2, # replace shade with shade2, everything else is unchanged
            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()

plot

like image 184
Z.Lin Avatar answered Dec 04 '25 15:12

Z.Lin