首页 文章

ggplot2中的中心绘图 Headers

提问于
浏览
168

嗨这个简单的代码(以及我今天早上的所有脚本)已经开始在ggplot2中给我一个偏离中心的 Headers

Ubuntu version: 16.04

R studio version: Version 0.99.896

R version: 3.3.2

GGPLOT2 version: 2.2.0

今天早上我刚刚安装了上面这个以试图解决这个问题....

dat <- data.frame(
time = factor(c("Lunch","Dinner"), levels=c("Lunch","Dinner")),
total_bill = c(14.89, 17.23)
)

# Add title, narrower bars, fill color, and change axis labels
ggplot(data=dat, aes(x=time, y=total_bill, fill=time)) + 
  geom_bar(colour="black", fill="#DD8888", width=.8, stat="identity") + 
  guides(fill=FALSE) +
  xlab("Time of day") + ylab("Total bill") +
  ggtitle("Average bill for 2 people")

enter image description here

2 回答

  • 87

    来自 ggplot 2.2.0 的发布消息:"The main plot title is now left-aligned to better work better with a subtitle" . 另请参见 ?theme 中的 plot.title 参数:"left-aligned by default" .

    正如@J_F所指出的,你可以添加 theme(plot.title = element_text(hjust = 0.5)) 来使 Headers 居中 .

    ggplot() +
      ggtitle("Default in 2.2.0 is left-aligned")
    

    enter image description here

    ggplot() +
      ggtitle("Use theme(plot.title = element_text(hjust = 0.5)) to center") +
      theme(plot.title = element_text(hjust = 0.5))
    

    enter image description here

  • 224

    answer by Henrik中所述,默认情况下 Headers 是左对齐的,从ggplot 2.2.0开始 . 通过将 Headers 添加到图中可以使 Headers 居中:

    theme(plot.title = element_text(hjust = 0.5))
    

    但是,如果您创建了许多绘图,则在任何地方添加此行可能会非常繁琐 . 然后,人们也可以改变ggplot的默认行为

    theme_update(plot.title = element_text(hjust = 0.5))
    

    运行此行后,之后创建的所有绘图将使用主题设置 plot.title = element_text(hjust = 0.5) 作为其默认值:

    theme_update(plot.title = element_text(hjust = 0.5))
    ggplot() + ggtitle("Default is now set to centered")
    

    enter image description here

    要返回原始ggplot2默认设置,您可以重新启动R会话或选择默认主题

    theme_set(theme_gray())
    

相关问题