0

If I place the legend below a plot made with ggplot2 via theme(legend.position = "bottom") I can't fit all the legend labels on the plot if they have around 20 to 25 characters. For some reason I can't reduce the space between the legend items, even if I use theme(legend.spacing.x = unit(0.00001, "cm")) (also below some value the space between legend items is not reduced any further).

Why does the white space between legend items increase so much with the length of the legend labels? See the three examples I provide, with very short, normal and long legend label lengths. I know you can make use of two or more rows for the legend items, however, with the long labels the white space is so large that you can only fit two per row.

data <-
  tibble(x = as.numeric(rep(c(1991:2020), each = 5)),
         y = as.numeric(rep(rep(20:11, each = 3), each = 5)),
         longlab = factor(paste0("thisisaverylonglegendlabel", rep(c(1:5), 30))),
         shortlab = factor(paste0("shortlab", rep(c(1:5), 30))),
         supershortlab = factor(paste0("l", rep(c(1:5), 30))))

data %>% 
  ggplot(aes(x = x, y = y, fill = longlab)) +
  geom_area() +
  theme(legend.position = "bottom")

https://i.stack.imgur.com/Qhs4A.jpg

data %>% 
  ggplot(aes(x = x, y = y, fill = normallab)) +
  geom_area() +
  theme(legend.position = "bottom")

https://i.stack.imgur.com/OSEwE.jpg

data %>% 
  ggplot(aes(x = x, y = y, fill = supershortlab)) +
  geom_area() +
  theme(legend.position = "bottom")

https://i.stack.imgur.com/vmB5x.jpg

Is there a way to reduce the legend spacing to a minimum (similar to the spacing in the plot with the super short labels)?

r-newbie
  • 149
  • 7

1 Answers1

0

These are the options to remove or adjust the padding in the legend:

  theme(legend.position = "bottom",
        legend.margin = margin(0, 0, 0, 0),
        legend.spacing.x = unit(0, "mm"),
        legend.spacing.y = unit(0, "mm"))

One option is to put the legend on two lines:

guides(fill = guide_legend(nrow = 2, byrow = TRUE)) +

However, I get this plot, without the distended legend you see: enter image description here

No explanation for the difference output, though.

Tech Commodities
  • 1,884
  • 6
  • 13
  • Ok, so the error seems to be the showtext package that I load to be able to use an imported font family. ```showtext_auto()```causes the problem. Good that I found the cause, however, I haven't found a solution until now.. someone else seems to have the same problem: https://stackoverflow.com/questions/69019574/reducing-spacing-between-items-in-ggplot2-horizontal-legend – r-newbie Feb 28 '23 at 13:25
  • Did you try `showtext_end()`? – Tech Commodities Feb 28 '23 at 13:57
  • Yes. I read in another post that this resolves the legend spacing problem but then the loaded font family does not work anymore (which I would still like to use). In my case, however, using ```showtext_end()``` did not have any effect. – r-newbie Feb 28 '23 at 20:54