在 ggplot 中使用 facets 在绘图区域外注释一次

Uma*_*mao 5 r ggplot2

我想在多面 ggplot 的绘图区域外添加注释。我可以获得我想要的注释,但它会针对每个方面重复。我怎样才能让这个注释只出现一次?

例如,要在左上角注释“XX”一次,我可以使用:

library("ggplot2")
ggplot(mtcars, aes(x = hp, y = mpg)) +
  geom_point() +
  facet_grid(.~cyl ) + 
  annotate("text", x = -20, y = 36, label = "XX") +
  coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off")
Run Code Online (Sandbox Code Playgroud)

注释图

然而,这实际上将其注释到每个方面的左上角。

我怎样才能让它只出现一次?

aos*_*ith 7

您可以使用tagin 在图形上放置单个标签标签labs()

ggplot(mtcars, aes(x = hp, y = mpg)) +
     geom_point() +
     facet_grid(.~cyl ) + 
     labs(tag = "XX") +
     coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

但是,这默认为“左上角”,这可能不是您想要的。您可以使用主题元素来移动它plot.tag.position,无论是作为坐标(在 0 和 1 之间要在绘图空间中)还是作为像"topright".

ggplot(mtcars, aes(x = hp, y = mpg)) +
     geom_point() +
     facet_grid(.~cyl ) + 
     labs(tag = "XX") +
     coord_cartesian(xlim = c(50, 350), ylim = c(10, 35), clip = "off") +
     theme(plot.tag.position = c(.01, .95))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明