2016-12-07 82 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) –