In this vignette of patchwork is explained how to combine multiple ggplots. One difficulty I encountered is to collect the legends and align/justify them properly when their titles are very different in number of characters.
Below is an example - I would like the 'mpg' legend to be also left justified / aligned and not centered beneath the 'Size' legend. Any suggestions? Note that, adding theme(legend.justification = "left")
doesn't solve the problem.
library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) +
geom_point(aes(mpg, disp, colour = mpg, size = wt)) +
guides(size = guide_legend(title = "Size - long title for the purpose of this example")) +
ggtitle('Plot 1')
p2 <- ggplot(mtcars) +
geom_boxplot(aes(gear, disp, group = gear)) +
ggtitle('Plot 2')
p3 <- ggplot(mtcars) +
geom_point(aes(hp, wt, colour = mpg)) +
ggtitle('Plot 3')
(p1 | (p2 / p3)) + plot_layout(guides = 'collect')
Created on 2019-12-16 by the reprex package (v0.3.0)
In the meantime, this was fixed by Ilia Kats.
Using & theme(legend.justification = "left")
(when keeping legends separate/aligned with plot) or + plot_layout(guides = 'collect')
(merging legends from plots) now just works.
Use remotes::install_github("thomasp85/patchwork")
to update patchwork
(if pre ~2020).
Detailed example:
library(ggplot2)
library(patchwork)
p1 <- ggplot(mtcars) +
geom_point(aes(mpg, disp, colour = mpg, size = wt)) +
guides(size = guide_legend(title = "Size - long title for the purpose of this example")) +
ggtitle('Plot 1')
p2 <- ggplot(mtcars) +
geom_boxplot(aes(gear, disp, group = gear)) +
ggtitle('Plot 2')
p3 <- ggplot(mtcars) +
geom_point(aes(hp, wt, colour = mpg)) +
ggtitle('Plot 3')
OP's case is fixed:
(p1 | (p2 / p3)) + plot_layout(guides = 'collect')
But the default case is still not aligned:
(p1 / p3)
Align by merging guides (now fixed):
(p1 / p3) + plot_layout(guides = 'collect')
Align by left justification (now fixed):
(p1 / p3) & theme(legend.justification = "left")
(This would be desirable if there are no shared legends between the two plots ( so this just an bad example for the use))
Created on 2020-09-10 by the reprex package (v0.3.0)
# Session info:
R version 4.0.1 (2020-06-06),
ggplot2 * 3.3.1 2020-05-28 [1] CRAN (R 4.0.0)
patchwork * 1.0.1.9000 2020-09-10 [1] Github (thomasp85/patchwork@82a5e03)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With