ggplot2 icon indicating copy to clipboard operation
ggplot2 copied to clipboard

Length of legend title affects justification of legend keys/labels?

Open orb16 opened this issue 7 years ago • 3 comments

This produces a nicely centred title (and centred legend text):

require(ggplot2)
data(iris)
ggplot(iris, aes(y = Sepal.Width, x = Petal.Width)) + 
geom_point(shape = 21, aes(fill = Species)) + 
guides(fill = guide_legend(title.position = "top", title.hjust = 0.5))  + 
scale_fill_manual("Species", values = c("orange", "black", "white")) 

Here changing the length of the legend title appears to affect the justification of the legend text:

ggplot(iris, aes(y = Sepal.Width, x = Petal.Width)) + 
geom_point(shape = 21, aes(fill = Species)) + 
guides(fill = guide_legend(title.position = "top", title.hjust = 0.5))  + 
scale_fill_manual("A really, really long title that is sometimes necessary involving species", 
values = c("orange", "black", "white")) 

Using ggplot2_2.1.0 and R version 3.2.4 Revised

orb16 avatar Nov 13 '16 23:11 orb16

Minimal reprex:

library(ggplot2)
df <- data.frame(x = c("a", "bbbbbbbbbbbbb"))

ggplot(df, aes(x = x, fill = x)) +
  geom_bar() +
  labs(fill = "A very very very long label") +
  theme(legend.box.just = "center")

I think the current behaviour is technically correct - the title is centered, but the legend box is not.

hadley avatar Nov 01 '17 17:11 hadley

This SO answer provides a way to center the legend box underneath the title: https://stackoverflow.com/a/48011882/4975218 The code is general and could be integrated into the legend drawing code. I might tackle it, but not for 2.3.0.

One downside to this approach is that if there are multiple legends then they will be centered relative to each other but not overall. A better solution would fix the overall case as well.

clauswilke avatar May 10 '18 21:05 clauswilke

I think this reaches beyond the currently provided theme settings... The title alignment is basically doing what it should, and so does legend.box.just since it aligns multiple legends with each others (and will thus not have any effect on single legend plots)

We will need a new setting that takes care of internal alignment of titles and keys with respect to each other

thomasp85 avatar Apr 13 '21 08:04 thomasp85