This is about organizing plots in R markdown document. Say we create three plots:
library(patchwork)
library(tidyverse)
a <- ggplot(mtcars, aes(mpg, wt)) + geom_point() + ggtitle("Plot A")
b <- ggplot(mtcars, aes(drat, wt)) + geom_point() + ggtitle("Plot B")
c <- ggplot(mtcars, aes(cyl, wt)) + geom_point() + ggtitle("Plot C")
My organization is:
Plot<- a+b+c +plot_layout(ncol = 2)
It’s OK. But what I really want is:
plot<- a /(b + c) +
plot_layout(ncol = 2)
Except that all three plots are the same size, the upper centered.
Something very similar can be done with plot_spacer():
plot<- plot_spacer() + a + plot_spacer() /(b + plot_spacer() + c)
But that decrease the size of the plots. Is there a way to keep the size of the plots, only center the upper one?
0
design <- "
#11#
2233"
wrap_elements(full = a) + b + c + plot_layout(design = design, widths = 1)
The wrap_elements
part is used to make the plots equal in width. (Though I haven’t been able to get them to be the same height without manually adding heights = c(1.2,1)
)
As the patchwork
author notes here, “the issue is that the y-axis of the top plot influences the width of plots spanning it’s location. The easiest way is to remove alignment from the top plot by putting it inside wrap_elements().”
The method provided by jon-spring should work if you don’t want to strictly center justification. With the latest patchwork
(version 1.3.0 https://github.com/thomasp85/patchwork/issues/386, you can now install it from the github), we can just remove the spaces of the y-axis when alignment (panel’ll still be aligned, this ensure the top plot is in the center).
knitr::opts_knit$set(upload.fun = identity)
library(ggplot2)
library(patchwork)
a <- ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
ggtitle("Plot A")
b <- ggplot(mtcars, aes(drat, wt)) +
geom_point() +
ggtitle("Plot B")
c <- ggplot(mtcars, aes(cyl, wt)) +
geom_point() +
ggtitle("Plot C")
free(a, "space", "l") + b + c +
plot_layout(design = "#11#
2233")
Created on 2024-09-14 with reprex v2.1.0
~
To better see the difference, let’s use the example from https://github.com/thomasp85/patchwork/issues/319.
If centered, the top plot panel should align the x-axis of bottom plot in value 6.
design <- "###AAAA###
###AAAA###
BBCCDDEEFF
JJKKLLMMNN"
f <- ggplot(mtcars, aes(x = cyl, y = mpg))
wrap_plots(wrap_elements(full = f),
f, f, f, f, f, f, f, f, f, f,
design = design
)
wrap_plots(free(f, "space", "l"),
f, f, f, f, f, f, f, f, f, f,
design = design
)
2