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

问题描述

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

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

如何在“全局”、整体绘图区域上指定单个标签的位置(类似于下面示例中 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),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

example_ggplot_output

谢谢!

解决方法

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

请看下面的代码。

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),colour = "grey20") + 
  facet_wrap(~vs,nrow = 2)

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

这是你想要的吗?

reprex package (v1.0.0) 于 2021 年 3 月 3 日创建

,

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

library(tidyverse)
library(cowplot)

p <- mtcars %>% 
  ggplot(aes(x = mpg,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,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 年 3 月 3 日创建