Skip to content
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

✨ Justification for legend keys #6279

Merged
merged 6 commits into from
Jan 28, 2025

Conversation

teunbrand
Copy link
Collaborator

@teunbrand teunbrand commented Jan 10, 2025

This PR aims to fix #3669.

It introduces a new theme element legend.key.justification to control the placement of legend keys when there is more space available than needed to display the key. This condition can be met by having text that is larger than the key or when keys have unequal sizes like in linewidth or size legends. I arrived at the conclusion that this should be a justification setting because it was unclear where exactly to place the key if it were just a boolean setting. Moreover, this nicely allows for justification settings in both the horizontal and vertical direction (see snapshot test).

Reprex from the issue, note that the keys in the the second row of the first legend no longer stretch:

devtools::load_all("~/packages/ggplot2")
#> ℹ Loading ggplot2
set.seed(15)

df <- data.frame(x=1:50, y=rnorm(50, 10, 2), var=rep(c("A","B","C","D","E"),10))
labs = c("A oneline","B oneline","C oneline", "D\ntwolines","E\ntwolines")
cols = c('#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00')


ggplot(df) + 
  geom_ribbon(aes(x=x, ymin=y-1, ymax=y+1, fill=var), alpha=0.3) +
  geom_line(aes(x=x, y=y, colour=var), alpha=0.3, linewidth=2) +
  scale_fill_manual(values=cols, labels = labs) +
  theme(legend.position="bottom",
        legend.title = element_blank(),
        legend.text = element_text(size = 14)) +
  guides(fill=guide_legend(ncol=3, byrow=TRUE)) +
  theme(legend.key.justification = "top")

Created on 2025-01-10 with reprex v2.1.1

Copy link
Member

@thomasp85 thomasp85 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! LGTM

@teunbrand teunbrand merged commit b9d1c79 into tidyverse:main Jan 28, 2025
13 checks passed
@teunbrand teunbrand deleted the unstretchy_legend_keys branch January 28, 2025 11:45
@Nova-Scotia
Copy link

Can't tell you how many scripts I can fix now that this is implemented!! Thank you so much for your work on this issue!!

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.

key height gets stretched when using multiline key-labels or large font size in the legend
3 participants