how to align the legend title to the middle of legend box in ggplot2?
Asked Answered
L

2

30

I want to move the legend title sex a little right to the horizontal center of legend box. I tried theme and guide_legend but failed. Both ways won't change the legend title position.

# example data from http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/
df1 <- data.frame(
    sex = factor(c("Female","Female","Male","Male")),
    time = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
    total_bill = c(13.53, 16.81, 16.24, 17.42)
)

library(ggplot2)
p <- ggplot(data=df1, aes(x=time, y=total_bill, group=sex, shape=sex, colour=sex)) +
    geom_line() + geom_point()

# no change
p + theme(legend.title = element_text(hjust = 0.5))
p + guides(color=guide_legend(title.hjust=0.5))

In addition, I am using ggplot2_2.2.0.

Lantz answered 7/12, 2016 at 5:28 Comment(0)
S
35

You need legend.title.align rather than legend.title:

p + theme(legend.title.align=0.5) 

enter image description here

Sharrisharron answered 7/12, 2016 at 5:37 Comment(2)
Apparently this doesn't work for long legend titles.Fredelia
@ClausWilke it works well for long titles if you break it with a newline: "\n"Kaycekaycee
S
1

Here is an update for more current versions of ggplot2. Running the accepted answer will proc a lifecycle warning:

The `legend.title.align` argument of `theme()` is deprecated as of ggplot2 3.5.0.
ℹ Please use theme(legend.title = element_text(hjust)) instead.

Funnily enough, @mt1022's original attempt is at aligning the legend text is now the official way of doing so.

p + theme(legend.title = element_text(hjust = 0.5))

enter image description here

Stow answered 18/7 at 22:9 Comment(1)
I like the new way of specifying legend title alignment. Another option is to remove the legend title. The legend labels are often self-descriptive.Lantz

© 2022 - 2024 — McMap. All rights reserved.