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

Legend size adjustment within guides #6339

Open
Breeze-Hu opened this issue Feb 19, 2025 · 3 comments · May be fixed by #6340
Open

Legend size adjustment within guides #6339

Breeze-Hu opened this issue Feb 19, 2025 · 3 comments · May be fixed by #6340

Comments

@Breeze-Hu
Copy link

Hi!

When I tried to adjust the legend.key.size in guides it doesn't seem to work as expected. But legend.key.spacing.y works fine.
When I include it in the theme(adjusting the whole legend?) , the code works very well.

I'm not sure if this is similar to the question below? Or is it a bug? If this behavior is indeed due to an underlying mechanism, wouldn’t it be preferable for the documentation to include a note about it, as is done for this issue?
#6263

Here is the code to reproduce the issue:

library(tidyverse)

data = tibble(x = rep(c('a','b'),each = 10),
              y = runif(20,min = 0, max=10))

ggplot(data = data, aes(x = x, y = y, fill = x))+
  geom_boxplot()+
  guides(fill = guide_legend(theme = theme(legend.key.spacing.y = unit(5,'lines'),
                                           legend.key.size = unit(3, 'lines')))
         )

Image

ggplot(data = data, aes(x = x, y = y, fill = x))+
  geom_boxplot()+
  guides(fill = guide_legend(theme = theme(legend.key.spacing.y = unit(5,'lines')))
  )+
  theme(legend.key.size = unit(3, 'lines'))

Image

@teunbrand
Copy link
Collaborator

teunbrand commented Feb 19, 2025

Thanks for the report! This is because the legend.key.width/legend.key.height are precomputed from the main theme, so setting the parent legend.key.size locally is ineffective. I'm not 100% convinced this is an actual bug, but I can see why this is confusing and we should consider changing this.

@teunbrand
Copy link
Collaborator

A more minimal reprex:

library(ggplot2)
big_keys <- theme(legend.key.size = unit(3, "cm"))

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

p + big_keys

p + guides(colour = guide_legend(theme = big_keys))

Created on 2025-02-19 with reprex v2.1.1

@Breeze-Hu
Copy link
Author

This is because the legend.key.width/legend.key.height are precomputed from the main theme, so setting the parent legend.key.size locally is ineffective.

Get!

I'm not 100% convinced this is an actual bug

I totally agree with this statement.

Looking forward to the follow up. Thank you!!!

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

Successfully merging a pull request may close this issue.

2 participants