28

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.

mt1022
  • 16,834
  • 5
  • 48
  • 71

1 Answers1

33

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

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

enter image description here

eipi10
  • 91,525
  • 24
  • 209
  • 285
  • 11
    Apparently this doesn't work for [long legend titles.](https://stackoverflow.com/questions/48000292/center-align-legend-title-and-legend-keys-in-ggplot2-for-long-legend-titles) – Claus Wilke Dec 28 '17 at 00:48
  • 3
    @ClausWilke it works well for long titles if you break it with a newline: `"\n"` – Dylan_Gomes Dec 13 '20 at 18:51