plot_annotations 通过 R 中的拼凑消失

plot_annotations disappear via patchwork in R

我正在尝试将两个 patchwork objects 绘制在一起。代码有效,但 plot_annotations 消失了。

如何解决这个问题?

数据+代码:

library(tidyverse)
library(patchwork)

#Plot 1
GG1 = ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
  geom_point()
#Plot 2
GG2 = ggplot(iris,aes(y=Sepal.Length,x=Sepal.Width))+
  geom_point()
#Plot 3
GG3 = ggplot(iris,aes(y=Petal.Width,x=Sepal.Width))+
  geom_point()
#Plot 4
GG4 = ggplot(iris,aes(y=Petal.Length,x=Petal.Width))+
  geom_point()


combine_1 =  GG1 + GG2 +
  plot_annotation(title = 'Combine plot 1',
                  theme = theme(plot.title = element_text(hjust = 0.5)))

combine_2 =  GG3 + GG4 +
  plot_annotation(title = 'Combine plot 2',
                  theme = theme(plot.title = element_text(hjust = 0.5)))

combine_1/combine_2

输出

据文档

,恐怕无法通过 plot_annotation 实现您想要的结果

... it will only have an effect on the top level plot.

但这将是一个不错的功能。

作为解决方法,您可以将标题添加到组合的子图中,如 textGrobs

备注:

  1. 为了完成这项工作,我必须将 textGrob 包裹在 wrap_elements 内。
  2. 我在设置 plot_layout 时也遇到了一些问题,这就是为什么我必须使用 plot_layout(heights = c(1, 10, 11)) 作为最终情节。
library(ggplot2)
library(patchwork)
library(grid)
#Plot 1
GG1 = ggplot(iris,aes(x=Sepal.Length,y=Sepal.Width))+
  geom_point()
#Plot 2
GG2 = ggplot(iris,aes(y=Sepal.Length,x=Sepal.Width))+
  geom_point()

title1 <- grid::textGrob(label = "Combine Plot1")
title2 <- grid::textGrob(label = "Combine Plot2")

combine_1 =  (wrap_elements(panel = title1) / (GG1 + GG2)) + plot_layout(heights = c(1, 10))
combine_2 =  (wrap_elements(panel = title2) / (GG1 + GG2)) + plot_layout(heights = c(1, 10))

(combine_1 / combine_2) +  plot_layout(heights = c(1, 10, 11))

EDIT 在回答 this 相关问题时,我想出了一种更简单的方法来添加多个地块,它通过将每个地块包装在内部来简单地将组合地块包装在一起patchwork::wrap_elements:

combine_1 =  (GG1 + GG2) & plot_annotation(title = "Combine Plot1") & theme(plot.title = element_text(hjust = .5))
combine_2 =  (GG1 + GG2) & plot_annotation(title = "Combine Plot2") & theme(plot.title = element_text(hjust = .5))

wrap_elements(combine_1) / wrap_elements(combine_2)