【问题标题】:Use annotate("rect") for one facet in ggplot when plotting time series on x-axis在 x 轴上绘制时间序列时,对 ggplot 中的一个方面使用 annotate("rect")
【发布时间】:2019-04-18 14:38:31
【问题描述】:

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

    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)
    

    这会产生所需的情节:

    【讨论】:

    • 仅供参考,这种方法重复矩形的次数与数据集中的行数一样多(这就是为什么你的矩形如此暗,所以你必须使alpha 如此小)。有several work-arounds to this,包括制作单行数据集,避免审美继承:geom_rect(data = data.frame(year = 2019), aes(xmin = 5, xmax = 8, ymin = 0, ymax = Inf), alpha = 0.3, fill="grey", inherit.aes = FALSE)
    • @aosmith 现在不知道inherit.aes,谢谢你的解释!
    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    相关资源
    最近更新 更多