ggplot2
ggplot2 copied to clipboard
Length of legend title affects justification of legend keys/labels?
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
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.
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.
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