Skip to content

Instantly share code, notes, and snippets.

@padpadpadpad
Created July 28, 2023 08:15
Show Gist options
  • Save padpadpadpad/ecb66af32dba33a4dc4a32da873e4fe7 to your computer and use it in GitHub Desktop.
Save padpadpadpad/ecb66af32dba33a4dc4a32da873e4fe7 to your computer and use it in GitHub Desktop.
Example of using patchwork and cowplot to arrange legends in a four panel plot.
# 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