Skip to content

Relative legend spacing #6431

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

teunbrand
Copy link
Collaborator

@teunbrand teunbrand commented Apr 15, 2025

This PR aims to fix #6417.

Briefly, it allows legend.spacing.{x/y} to be null-units, indicating that the space between legends should be stretched to fit the available space.

It is not what was proposed in the issue, but I think it allows the 'spirit' of the request and is much more maintainable and easier to reason about than independent justifications for non-inside legends.

Some examples. Nevermind what is displayed, the example is a little bit contrived, but the point is the placement of the colour bars. Here is standard use, it distributes the legends across the available space.

devtools::load_all("~/packages/ggplot2/")
#> ℹ Loading ggplot2

p <- ggplot(mpg, aes(displ, hwy)) +
  geom_point(aes(colour = cty, fill = hwy))

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

Just as a reminder, we also allow guides to be 'stretchy' i.e. let some components take up the available space.

stretchy <- guide_colourbar(theme = theme(
  legend.key.height = unit(1, "null"),
  legend.background = element_rect(colour = "grey")
))

p <- p + guides(
  colour = stretchy,
  fill   = stretchy
)

p

Combining stretchy guides with stretchy also works. Note that the space in between is roughly the same size as the bars. It doesn't work out in a very exact manner due to several absolutely sized margins, but it works in approximation.

p + theme(legend.spacing.y = unit(0.5, "null"))

Created on 2025-04-15 with reprex v2.1.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Independent justification of legends
1 participant