One shared legend for a cowplot grid in R
There is a vignette that shows how to do this.
The approach is to build your plots with the legend hidden theme(legend.position="none")
.
Then extract the legend grob from one of those objects.
grobs <- ggplotGrob(pfour)$grobs
legend <- grobs[[which(sapply(grobs, function(x) x$name) == "guide-box")]]
Then plot the legend as a seperate 'plot'. To have the legend at to the right you might do:
# build grid without legends
pgrid <- plot_grid(pone, ptwo, pthree, pfour, ncol = 2)
# add legend
p <- plot_grid(pgrid, legend, ncol = 2, rel_widths = c(1, .1))
You can use ggarrange
function from ggpubr
package. It has a logical argument common.legend
. You just need to set it TRUE
. In your case a code chunk will be:
library(ggpubr)
ggarrange(ponezoom, ptwozoom, pthreezoom, pfourzoom,
align='h', labels=c('A', 'B','C','D'),
common.legend = T)
See example with mtcars
dataset:
library(tidyverse)
library(ggpubr)
# Create first plot
mtcars %>%
ggplot(aes(mpg, hp, color = factor(cyl))) +
geom_point(size = 2) +
theme_minimal()-> plot1
# Create second plot
mtcars %>%
ggplot(aes(disp, drat, color = factor(cyl))) +
geom_point(size = 2) +
theme_minimal() -> plot2
# Create grid
ggpubr::ggarrange(plot1, plot2, # list of plots
labels = "AUTO", # labels
common.legend = T, # COMMON LEGEND
legend = "bottom", # legend position
align = "hv", # Align them both, horizontal and vertical
nrow = 2) # number of rows
Voila: