如何将图例标题与ggplot2中的图例中间对齐? [英] how to align the legend title to the middle of legend box in ggplot2?

查看:925
本文介绍了如何将图例标题与ggplot2中的图例中间对齐?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图例标题 sex 右移一点到图例框的水平中心。我试过主题 guide_legend ,但失败了。这两种方式不会改变图例的标题位置。

 #来自http://www.cookbook-r.com的示例数据/图/传说_(ggplot2)/ 
df1 < - data.frame(
sex = factor(c(女,女,男,男)),
时间=因子(c(午餐,晚餐,午餐,晚餐),水平= c(午餐,晚餐)),
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 =
$ b#不变
p + theme(legend.title = element_text(hjust = 0.5))
p + guides(color = guide_legend(title.hjust = 0.5))

另外,I我使用ggplot2_2.2.0。

解决方案

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

  p +主题title.align = 0.5)


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.

解决方案

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

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

这篇关于如何将图例标题与ggplot2中的图例中间对齐?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆