Skip to content

legend.spacing.{x/y} is not inherited in guide_legend().Β #4977

@teunbrand

Description

@teunbrand

I was working on some code related to legends, and found out that the legend guide doesn't do inheritance of the legend.spacing.{x/y} theme elements from the parent legend.spacing element.

When I set a plot with legend.spacing = *some largish number*, I expect the spacing between the legend keys to increase relative to the default. Note that in the plot below, we can dispense with the theme() call and get exactly the same plot.

library(ggplot2)

p <- ggplot(mpg, aes(displ, cty)) +
  geom_point(aes(colour = factor(cyl))) +
  guides(colour = guide_legend(byrow = TRUE)) # we need byrow here, see #4352

p + theme(legend.spacing = unit(1, "cm"))

Instead, I would have expected this:

p + theme(legend.spacing.y = unit(1, "cm"))

Contrary to many issues posted about theme inheritance, the child element is truly empty in the default theme.

theme_get()$legend.spacing.y
#> NULL

Created on 2022-09-03 by the reprex package (v2.0.1)

This is not a hard fix, and I'm happy to take it along in #4879, but it would be a visual change.* Would the maintainers agree to adjust this?

* It would be a visual change because currently, legend.spacing.{x/y} is typically NULL in the default theme, which sets the spacing relative to the title text in the lines below (which would no longer occur if we adjust this):

ggplot2/R/guide-legend.r

Lines 337 to 338 in a58b48c

hgap <- width_cm(theme$legend.spacing.x %||% (0.5 * unit(title_fontsize, "pt")))
vgap <- height_cm(theme$legend.spacing.y %||% (0.5 * unit(title_fontsize, "pt")))

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions