2016-12-07 94 views
6

我想将图例标题sex稍微向右移动到图例框的水平中心。我试过themeguide_legend但失败。这两种方式都不会改变图例的标题位置。如何将图例标题与ggplot2中的图例框对齐?

# 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)) 

另外,我使用的是ggplot2_2.2.0。

回答

6

您需要legend.title.align而不是legend.title

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

enter image description here

+0

谢谢。这解决了我的问题。 – mt1022

+2

显然这不适用于[long legend titles。](https://stackoverflow.com/questions/48000292/center-align-legend-title-and-legend-keys-in-ggplot2-for-long-legend -titles) –