分面时添加多个注解

Adding multiple annotations when faceting

我无法将多个注释(使用向量)添加到带有小平面的绘图中。

例如:

library(tidyverse) # ggplot2_3.3.0

tibble(t = 1:100) %>% 
  crossing(id = LETTERS[1:2]) %>% 
  group_by(id) %>% 
  mutate(y = cumsum(rnorm(n()))) %>% 
  ggplot(aes(t, y)) + # perhaps add `group = id` if you don't facet by `id`
  facet_wrap(vars(id)) + # (1)
  annotate('rect', xmin = 20, xmax = 30, ymin = -Inf, ymax = Inf, fill = 'grey60') + # (2)
  annotate('rect', xmin = 30, xmax = 40, ymin = -Inf, ymax = Inf, fill = 'grey70') + # (2)
  annotate('rect', xmin = 40, xmax = 50, ymin = -Inf, ymax = Inf, fill = 'grey80') + # (2)
  annotate('rect', xmin = 50, xmax = 60, ymin = -Inf, ymax = Inf, fill = 'grey90') + # (2)
  # annotate('rect', ymin = -Inf, ymax = Inf,                # (3)
  #          xmin = seq(20, by=10, len=4),                   # (3)
  #          xmax = seq(30, by=10, len=4),                   # (3)
  #          fill = paste0('grey', seq(60, by=10, len=4))) + # (3)
  geom_line() +
  theme_light()

以上代码生成了所需的图(特别是,我希望在所有方面都使用相同的注释)。但是,annotate 命令重复了四次;此外 annotate 的帮助页面显示 "the properties of the geoms are ... passed in as vectors"。 因此,很自然地要尝试注释掉第 (2) 行,并取消注释第 (3) 行。 不幸的是,这会产生错误

Error: Aesthetics must be either length 1 or the same as the data (8): fill

请注意,如果您另外注释掉第 (1) 行(并可选择将 group = id 添加到美学中),则它不会生成错误。

有关 ggplot2 的这种行为的讨论,请参阅 gihub。由于问题已关闭,据我所知,您无法通过使用 annotate 来解决这个问题。但是,要实现您想要的效果,您可以像这样简单地使用 geom_rect

library(tidyverse) # ggplot2_3.3.0

df_annotate <- data.frame(
  xmin = seq(20, 50, 10),
  xmax = seq(30, 60, 10),
  ymin = -Inf,
  ymax = Inf,
  fill = paste0("grey", seq(60, 90, 10))
)

tibble(t = 1:100) %>% 
  crossing(id = LETTERS[1:4]) %>% 
  group_by(id) %>% 
  mutate(y = cumsum(rnorm(n()))) %>% 
  ggplot() + 
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill), data = df_annotate) +
  geom_line(aes(t, y)) +
  scale_fill_identity() +
  facet_wrap(vars(id)) +
  theme_light()

reprex package (v0.3.0)

于 2020-05-28 创建

编辑 使用ggnewscale可以有第二个或...填充比例:

library(tidyverse) # ggplot2_3.3.0
library(ggnewscale)

df_annotate <- data.frame(
  xmin = seq(20, 50, 10),
  xmax = seq(30, 60, 10),
  ymin = -Inf,
  ymax = Inf,
  fill = paste0("grey", seq(60, 90, 10))
)

df <- tibble(t = 1:100) %>% 
  crossing(id = LETTERS[1:4]) %>% 
  group_by(id) %>% 
  mutate(y = cumsum(rnorm(n())))

ggplot() + 
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill), data = df_annotate) +
  scale_fill_identity() +
  new_scale_fill() +
  geom_area(data = df, aes(t, y, fill = id)) +
  facet_wrap(vars(id)) +
  theme_light()

reprex package (v0.3.0)

于 2020-05-29 创建