在 x 轴上绘制时间序列时,对 ggplot 中的一个方面使用 annotate("rect")

Hug*_*anp 4 r annotate facet ggplot2

我在构面中绘制不同的时间序列,并且我想使用 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") +
Run Code Online (Sandbox Code Playgroud)

我正在使用的代码是:

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))
Run Code Online (Sandbox Code Playgroud)

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

Cod*_*oob 6

Annotate不能这样做,因为您无法为它提供分面变量 ( year) 但是您可以使用geom_rect. 为此,您必须传递一个包含分面变量 ( 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)
Run Code Online (Sandbox Code Playgroud)

这将产生所需的情节:

在此处输入图片说明

  • 仅供参考,这种方法重复矩形的次数与数据集中的行数一样多(这就是为什么您的矩形如此黑暗,因此您必须将“alpha”设置得如此之小)。有 [几种解决方法](/sf/ask/3045799151/),包括制作单行数据集避免审美继承:`geom_rect(data = data.frame(year = 2019), aes(xmin = 5, xmax = 8, ymin = 0, ymax = Inf), alpha = 0.3, fill="grey", inherit。 aes = FALSE)`。 (3认同)