Shared legend for a cowplot grid in R
In this article, we will discuss how to create a cowplot grid with the shared legend in the R Programming language.
To do this first we will make a basic cowplot grid with two plots having their own legends separately. To do so using the cowplot grid package in the R Language we use the plot_grid() function and pass all the plots that we need in the grid as parameters.
Syntax: plot_grid(plot1,plot2,label=<label-vector>, ncol, nrow)
A basic cowplot grid with two plots having separate legends.
Shared Legend cowplot grid
To create a cowplot grid with shared legend there is no built-in method but the functionality can be achieved by following these steps:
Step 1: Create plots to be put in the grid without legend using:
plot + theme(legend.position = "none")
Step 2: Now combine both plots using the plot_grid() function and store that in a variable:
combined_plot<-plot_grid(plot1, plot2, ...... ncol)
Step 3: Now we extract the legend from one of the above plots to put it in the combined plot using:
legend <- get_legend( plot1 )
Step 4: Finally combine the combined plot with the derived legend using the plot_grid function to get the desired look for the shared legend plot.
plot_grid(combined_plot, legend, ncol)
Here, is an implementation of the above approach to get a cowplot grid with shared legend.