在x轴上绘制时间序列时,在ggplot中对一个面使用注释(“rect”)

问题描述 投票:1回答:1

我在facet中绘制了不同的时间序列,我想使用annotate()为其中一个方面创建不同的背景颜色。一个方面代表2018年的最后15周(第38-52周),而另一个方面代表2019年的前15周(第1-15周)。我想在2019年仅改变5-8周的背景颜色。但是,当我尝试这样做时,R将2018年x轴的范围从第38-52周改为第1-52周。

我试图在2019年的情节中仅创建一个5-8周的矩形,如下所示:

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

我使用的代码是:

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

我希望有两个方面:一个是2018年的结果,x轴范围在38-52之间,另一个是结果为2019,x轴范围在1-15之间。实际结果是2018的结果,x轴范围在1-52之间,一个结果为2019,x轴范围在1-15之间。

r ggplot2 facet annotate
1个回答
2
投票

Annotate不能这样做,因为你无法提供你的facetting变量(year),但是你可以使用geom_rect来做到这一点。为此,您必须传递包含facetting variabele(year)的数据框:

感谢@aosmith,现在geom_rect只绘制一次:

  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)

这会产生所需的图:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.