Use annotate("rect") for one facet in ggplot when plotting time series on x-axis
Asked Answered
C

1

5

I'm plotting different time series in facets and I would like to use annotate() to create a different background color for only one of the facets. One facet represents the last 15 weeks of 2018 (week 38 - 52) while the other facet represents the first 15 weeks of 2019 (week 1 - 15). I would like to change the background color for only weeks 5-8 in 2019. However, when I try to do that R changes the range of the x-axis of the 2018 from week 38-52 to week 1-52.

I have tried to create a rectangle for only weeks 5-8 in the 2019 plot as follows:

annotate("rect", xmin = 5, xmax = 8, min = 0, ymax = Inf, alpha = 0.3, fill="grey") +

The code I am using is:

library(ggthemes)
week <- c(38:52, 1:15)
minutes <- sample(160, 30, replace=T)
year <- c(rep(2018, 15), rep(2019,15))
dat <- data.frame(year, week, minutes)

ggplot(dat, aes(week, minutes, group=year)) +
  annotate("rect", xmin = 5, xmax = 8, min = 0, ymax = Inf, alpha = 0.3, fill="grey") +
  geom_line(size=1, color="black") +
  geom_point(size=2, color="black") +
  theme_fivethirtyeight() +
  facet_wrap(~ year, scales = "free") +
  scale_y_continuous(limits=c(0,200))

I expect to have two facets: one with the results of 2018 with an x-axis range between 38-52, and one with the results of 2019 with an x-axis range between 1-15. The actual result is one with the results of 2018 with an x-axis range between 1-52, and one with the results of 2019 with an x-axis range between 1-15.

Calendra answered 18/4, 2019 at 14:38 Comment(0)
N
7

Annotate cannot do this since you can't supply it with your facetting variable (year) however you can do this using geom_rect. To do so you have to pass a dataframe containing the facetting variabele (year):

Thank to @aosmith , now the geom_rect is only drawn once:

  ggplot(dat, aes(week, minutes, group=year)) +
  geom_line(size=1, color="black") +
  geom_point(size=2, color="black") +
  facet_wrap(~ year, scales = "free") +
  theme_fivethirtyeight() +
  scale_y_continuous(limits=c(0,200)) +
  geom_rect(data = data.frame(year = 2019), aes(xmin = 5, xmax = 8, ymin = 0, ymax = Inf), alpha = 0.3, fill="grey", inherit.aes = FALSE)

This produces the desired plot:

enter image description here

Narcoanalysis answered 18/4, 2019 at 14:55 Comment(2)
Just FYI, this approach repeats the rectangle as many time as you have rows in the dataset (which is why your rectangle was so dark so you had to make alpha so small). There are several work-arounds to this, including making a single row dataset and avoiding aesthetic inheritance: geom_rect(data = data.frame(year = 2019), aes(xmin = 5, xmax = 8, ymin = 0, ymax = Inf), alpha = 0.3, fill="grey", inherit.aes = FALSE).Slemmer
@Slemmer Didn't now about the inherit.aes, thankyou for explaining!Narcoanalysis

© 2022 - 2024 — McMap. All rights reserved.