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

标签 r ggplot2 facet annotate

我在构面中绘制不同的时间序列,并且我想使用 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 之间。

最佳答案

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)

这将产生所需的情节:

enter image description here

关于r - 在 x 轴上绘制时间序列时,对 ggplot 中的一个方面使用 annotate ("rect"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55748379/

相关文章:

python - 在 Pandas 中结合 FacetGrid 和双 Y 轴

r - 如何键入哈希键?

r - 如何调整使用 R 和 ggplot2 创建的箱线图中的框的大小以考虑不同箱线图中的不同频率?

mongodb - 在 MongoDB Spring Data 中使用多个方面

java - Elasticsearch 方面限制

r - 在 ggplot2 中指定特定形状

r - `stat_smooth()` : object 'C_crspl' not found 计算失败

r - R中的高阶(或非常高阶)多项式回归(或替代?)

r - 列内的 Str_sort,同时保留 data.frame 中的顺序

r - ggarrange : combining multiple plots with shared y and x axis: arrange for only one shared y axis while keeping plots in same proportion