Reputation: 2033
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
Upvotes: 4
Views: 1718
Reputation: 124438
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:
textGrob
s inside wrap_elements
.plot_layout
that's why I had to use plot_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))
EDIT When answering this related question I was able to come up with an easier approach to add multiple plots which simply wraps the combined plots together by wrapping each inside 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)
Upvotes: 6