首页 > 解决方案 > plot_annotations 通过 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

输出

在此处输入图像描述

标签: rggplot2patchwork

解决方案


plot_annotation根据文档,恐怕无法通过您想要的结果来实现

...它只会对顶层情节产生影响。

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

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

笔记:

  1. 为了完成这项工作,我必须将textGrobs 包裹在里面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))

编辑在回答这个相关问题时,我能够想出一种更简单的方法来添加多个图,该方法只需将组合图包装在一起,方法是将每个图包装在里面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)


推荐阅读