Last active
April 20, 2023 07:57
-
-
Save padpadpadpad/37b256d96a0f59c66abbca8ff9e37c53 to your computer and use it in GitHub Desktop.
An example of aligning plots using patchwork and having better control of the legend position.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# example of using cowplot and patchwork to make a plot with legends in the bottom right of a four panel plot | |
# load in packages | |
librarian::shelf(tidyverse, patchwork, cowplot) | |
# make a random plot with colour | |
p1 <- ggplot(mpg, aes(hwy, cty, col = class)) + | |
geom_point() | |
# make other plot with colour on | |
p2 <- ggplot(mpg, aes(hwy, displ, col = class)) + | |
geom_point() | |
# third plot with different legend | |
p3 <- ggplot(mpg, aes(displ, hwy, col = drv)) + | |
geom_point() | |
# make patchwork | |
p1 + p2 + p3 + plot_layout(ncol = 2) | |
# try collect legends | |
p1 + p2 + p3 + plot_layout(ncol = 2, guides = 'collect') & theme(legend.position = 'right') | |
# this works but you cannot control position of the legends very well | |
# grab legends using cowplot | |
legend1 <- get_legend(p1) | |
legend2 <- get_legend(p3) | |
# put them side by side | |
legends <- cowplot::plot_grid(legend1, legend2, ncol = 2, align = 'v') | |
# make plot and turn off legend globally | |
p1 + p2 + p3 + legends + plot_layout(ncol = 2) & theme(legend.position = 'none') | |
# can also put the legend on top of each other | |
legends <- cowplot::plot_grid(legend1, legend2, ncol = 1, align = 'v') | |
p1 + p2 + p3 + legends + plot_layout(ncol = 2) & theme(legend.position = 'none') | |
# there are loads of otehr ways to control the layout of the plot - see https://patchwork.data-imaginist.com/articles/guides/layout.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment