如何将单个注释添加到整体 ggplot 图而不是每个方面

How to add single annotation to overall ggplot plot and not to each facet

我有一个带有两个方面的 ggplot,每个方面都包含相同的自定义添加参考线。我想为每一行添加一个注释标签,并根据整个图上的位置指定每个标签的位置。

我尝试使用 annotate 添加标签,但这会为每个单独的面添加标签。

如何在 'global' 上指定单个标签的位置,整个绘图区域(类似于 xylegend.position 中的表现下面的示例)何时涉及方面?

library(ggplot2)

p <- mtcars %>% 
  ggplot(aes(x = mpg, y = disp, colour = am)) + 
  geom_point() + 
  geom_vline(aes(xintercept = 15), 
             linetype = "dotted",
             colour = "grey20") + 
  geom_vline(aes(xintercept = 25), 
             linetype = "dotted",
             colour = "grey20") + 
  facet_wrap(~vs, nrow = 2)

# desired behaviour is to position labels using x and y of overall plot area, as per positioning of legend 
p <- p + 
  # x and y refer to positions on overall plot here, not to values of variables within individual facets
  theme(legend.position = c(x = 0.9, y = 0.5))

# failed attempt adds labels to each facet
p <- p + 
  # x and y refer to individual facets/values of x and y variables here
  annotate("text", x = 15 , y = 0.5,
           label = "This label\nshould be on midpoint of y", 
           colour = "grey50") +
  annotate("text", x = 25 , y = 0.75,
           label = "This label\nshould be 3/4 up plot", 
           colour = "grey50")
 
# show plot
p

谢谢!

您可以使用 grid::grid.text() 在 canvas 中放置特定标签。多次使用它来实现你想要的。当然,也要调整标签的位置。

请看下面的代码。

library(ggplot2)
library(magrittr)
library(grid)

p <- mtcars %>% 
  ggplot(aes(x = mpg, y = disp, colour = am)) + 
  geom_point() + 
  geom_vline(aes(xintercept = 15), 
             linetype = "dotted",
             colour = "grey20") + 
  geom_vline(aes(xintercept = 25), 
             linetype = "dotted",
             colour = "grey20") + 
  facet_wrap(~vs, nrow = 2)

p
grid.text("text1", x = 0.5, y = 0.5)
grid.text("text2", x = 0.5, y = 0.75)

这是你想要的吗?

reprex package (v1.0.0)

创建于 2021-03-03

请注意,任何此类注释都会有些老套,需要仔细调整标签的位置。我认为最方便的应该是使用 patchwork 或 cowplot 进行自定义注释。 Cowplot offers specific functionality for plot labelling.

library(tidyverse)
library(cowplot)

p <- mtcars %>% 
  ggplot(aes(x = mpg, y = disp, colour = am)) + 
  geom_point() + 
  geom_vline(aes(xintercept = 15), 
             linetype = "dotted",
             colour = "grey20") + 
  geom_vline(aes(xintercept = 25), 
             linetype = "dotted",
             colour = "grey20") + 
  facet_wrap(~vs, nrow = 2) +
  theme(legend.position = c(x = 0.9, y = 0.5))

# desired behaviour is to position labels using x and y of overall plot area, as per positioning of legend 
ggdraw(p) + draw_plot_label(x = c(.2,.6), y = c(.6,.6), 
                       label =  c("This label\nshould be on midpoint of y",  "This label\nshould be 3/4 up plot"),
                       hjust = 0, size = 9)

reprex package (v1.0.0)

于 2021-03-03 创建