1

I need to make an arrange of plots in which each row of plots shares a common legend. All plots share the same units for y and x-axis. Below I show how my arrange of plots looks like:

enter image description here

I extract the common legend for each row as a plot and then I add it as an additional column in my arrange.

As you can see, the column with the legends "consume" a lot of space in the arrange, what could I do to reduce their margins in favour of the other two columns?

I used plot_grid because I saw in this link that you can create common x and y-axis titles using ggdraw.

Dekike
  • 1,264
  • 6
  • 17

1 Answers1

1

You can use the rel_widths argument of plot_grid. Here's a reproducible example:

library(ggplot2)
library(cowplot)
library(ggpubr)
theme_set(theme_cowplot())

df <- data.frame(x = 1:12, y = (1:12)^2)
df$grp = c('Some', 'Things', 'In a legend')

p <- ggplot(df, aes(x, y, color=grp)) + geom_point()
leg <- get_legend(p)
leg <- as_ggplot(leg)
p = p + theme(legend.position = "none")

plot_grid(
  p, p, leg, 
  p, p, leg,
  ncol = 3, rel_widths=c(2,2,1)
)

enter image description here

dww
  • 30,425
  • 5
  • 68
  • 111
  • Thanks @dww, one doubt, If I want to change some legend aspects (e.g. size), should I do it in the plots before extracting the legend or can I indicate something in `plot_grid`? – Dekike May 24 '20 at 11:56
  • You should make your plots and legends look how you want them first. Only use plot_grid to arrange the final products. – dww May 24 '20 at 12:31
  • Hi again @dww. I am sorry for disturbing you. I wanted to ask you if you could help me with the doubt I faced in this post: https://stackoverflow.com/questions/62004515/how-to-align-legends-included-in-the-plots-of-the-last-column-of-an-arrange-of-p . As you can see, the question is similar than here, but the difference is that there I was trying to align legends that have different width. In that post I make a reference to another post in which you offered a solution for this. However, as you can see in my case, the solution you propose in a different post doesn't work in my case. – Dekike May 25 '20 at 21:01
  • One solution is what the user Tung recommended me: the use of the package `patchwork`. Firstly I was happy with this solution. However, I have found a problem with this package that I got to solve using `plot_grid`. After the arrangement of the plots, I want to add a common X and Y label, and I have found how to do it with `plot_grid` (https://stackoverflow.com/questions/61997737/how-to-add-one-common-y-and-x-label-for-an-arrange-of-plots-and-also-a-label-for) but not with `plot_layout`. So, if you would know how to align legends in the case I linked in the previous comment, I'd appreciate it. – Dekike May 25 '20 at 21:08