Search code examples
rggplot2

How to reduce vertical margin between rows in ggplot legend


I want to have a vertically stacked legend (here, for size and colour), but I would want to reduce the space between the "shape" row and the "colour" row

library(ggplot2)
a <- cbind.data.frame(s=factor(rep(c(4,5), each=10)),
                      col=rep(c(1,2), 10),
                      x=runif(n = 10),
                      y=runif(n = 10))

plot_a <- ggplot(data = a, aes(x=x, y=y, shape=s, color=col))+
  geom_point()
plot_a + theme(legend.position = 'bottom', legend.box="vertical")

In the plot above, I would want less separation between the "s" and "col" legends:enter image description here

This is what I have tried, without being able to find how to modify this margin

plot_a+theme(legend.position = 'bottom',
             legend.box="vertical", 
             legend.key.spacing.y = unit(.2, "cm")) ## no change
plot_a+theme(legend.position = 'bottom',
             legend.box="vertical", 
             legend.key.size = unit(.7, "cm")) ## this changes size of keys but not margin

plot_a+theme(legend.position = 'bottom',
             legend.box="vertical", 
             legend.key.spacing = unit(.1, "cm")) ## this changes space between items of the same legend

thanks for your help!


Solution

  • To reduce the vertical spacing between the legends use legend.spacing.y and if that is not sufficient reduce or remove the margin around each legend using legend.margin:

    library(ggplot2)
    
    a <- data.frame(
      s = factor(rep(c(4, 5), each = 10)),
      col = rep(c(1, 2), 10),
      x = runif(n = 10),
      y = runif(n = 10)
    )
    
    plot_a <- ggplot(data = a, aes(x = x, y = y, shape = s, color = col)) +
      geom_point()
    
    plot_a +
      theme(
        legend.position = "bottom",
        legend.box = "vertical",
        legend.spacing.y = unit(0, "pt"),
        legend.margin = margin()
      )
    

    enter image description here