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.
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