简体   繁体   中英

Use annotate(“rect”) for one facet in ggplot when plotting time series on x-axis

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.

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM