如何将图例标题与ggplot2中图例框的中间对齐?

mt1*_*022 12 r legend ggplot2

我想将图例标题sex稍微移动到图例框的水平中心.我试过themeguide_legend,但失败了.两种方式都不会改变图例标题的位置.

# 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))
Run Code Online (Sandbox Code Playgroud)

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

eip*_*i10 13

你需要legend.title.align而不是legend.title:

p + theme(legend.title.align=0.5) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 显然这不适用于[长篇传奇游戏.](/sf/ask/3360020471/标题) (4认同)
  • @ClausWilke,如果你用换行符来打破它,它对于长标题来说效果很好:`“\ n”` (3认同)