I am trying to plot two patchwork
objects
together. The code works but plot_annotations
disappear.
How can this be fixed?
Data code:
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
Output
CodePudding user response:
I'm afraid that your desired result could not be achieved via plot_annotation
as according to the docs
... it will only have an effect on the top level plot.
But it would be a nice feature.
As a workaround you could add titles to your combined subplots as textGrobs
.
Notes:
- To make this work I had to wrap the
textGrob
s insidewrap_elements
. - I also encountered some issues with setting the
plot_layout
that's why I had to useplot_layout(heights = c(1, 10, 11))
for the final plot.
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))
Created on 2021-11-15 by the reprex package (v2.0.1)