【问题标题】:how to align the legend title to the middle of legend box in ggplot2?如何将图例标题与 ggplot2 中图例框的中间对齐?
【发布时间】:2017-04-21 23:01:03
【问题描述】:

我想将图例标题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))

另外,我用的是ggplot2_2.2.0。

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

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

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

    【讨论】:

    • 显然这不适用于long legend titles.
    • @ClausWilke 如果你用换行符打破它,它适用于长标题:"\n"
    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 2020-06-01
    相关资源
    最近更新 更多