Skip to content

guide_legend ignores legend.spacing.(x/y) depending on byrow #4352

@teunbrand

Description

@teunbrand

Hello there,

I apologise in advance if I submit issues too frequently; I do really appreciate all the good work you put into ggplot2.
By default, a legend appears to ignore the legend.spacing.y theme setting.

library(ggplot2)

p <- ggplot(mtcars, aes(mpg, fill = as.factor(cyl))) +
  geom_density() +
  theme(legend.spacing.y = unit(0.5, "cm"))
p

However, when byrow = TRUE in the guide, the legend.spacing.y is applied as expected.

p + guides(fill = guide_legend(byrow = TRUE))

Created on 2021-02-22 by the reprex package (v1.0.0)

For horizontal legend layouts, legend.spacing.x is ignored when byrow = TRUE, which is opposite to the vertical case.

ggplot(mtcars, aes(mpg, fill = as.factor(cyl))) +
  geom_density() +
  theme(legend.spacing.x = unit(0.5, "cm"),
        legend.position = "bottom") +
  guides(fill = guide_legend(label.position = "top",
                             byrow = TRUE))

I was surprised by this as I would have expected the legend.spacing to be applied regardless of the layout order of the keys, but I'm likely not aware of the considerations going in to this. I believe the code controlling the legend spacing and gaps sometimes interleave()s the label/key sizes with spacings, and sometimes doesn't, conditional on the byrow argument.

In an earlier comment (#3587 (comment)), it was proposed to get rid of the legend spacing, but I think there is a use-case for the spacing for the keys (the text margins maybe less so). Would it be a good idea to always interleave the spacing regardless of the byrow argument?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions