rggplot2patchwork

Increase item spacing in collected legend


patchwork provides an option to use only one legend in case the legend is identical across different sub-panels.

Changing the vertical spacing between legend items does not work as I would expect for this minimal working example:
Whatever value I insert for the legend.spacing.y option, the result (i.e. graphical output) stays the same.

library(ggplot2)
library(patchwork)

my_plot <- ggplot(iris, aes(Sepal.Length, Petal.Length, col=Species)) +
             geom_point()

my_plot + guide_area() + my_plot + 
  plot_layout(guides='collect') + 
  theme(legend.byrow=TRUE, legend.spacing.y=unit(1,'cm'))

I'm using ggplot2 version 3.5.2 and patchwork version 1.3.1.

I found an older report about surprising behaviour concerning vertical spacing of legend items, but this was fixed in the meantime and my code would also work around this problem.


Solution

  • Regardless of patchwork, the theme component legend.spacing is for space between multiple legends, not between elements in a single legend/guide. I think you want legend.key.height=. It will need to be applied to all guides that are to be collected, otherwise it appears that patchwork thinks them different enough to not combine.

    For instance, your plot with just one guide spaced:

    my_plot + guide_area() + my_plot + 
      plot_layout(guides='collect') + 
      theme(legend.key.height=unit(3,'cm'))
    

    ggplot patchwork with guides not collected

    Now applying the same theme to both legends,

    (my_plot + theme(legend.key.height=unit(3,'cm'))) +
      guide_area() +
      my_plot + 
      plot_layout(guides='collect') + 
      theme(legend.key.height=unit(3,'cm'))
    

    ggplot patchwork with guides correctly collected/combined