ggplot2中的中心绘图标题

时间:2016-11-18 11:18:31

标签: r ggplot2

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

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

4 个答案:

答案 0 :(得分:257)

来自ggplot 2.2.0的发布消息:"The main plot title is now left-aligned to better work better with a subtitle"。另请参阅plot.title中的?theme参数:&#34;默认情况下左对齐&#34;。

正如@J_F指出的那样,您可以添加theme(plot.title = element_text(hjust = 0.5))来使标题居中。

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

答案 1 :(得分:107)

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

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())

答案 2 :(得分:5)

ggeasy程序包具有一个名为easy_center_title()的函数来执行此操作。我发现它比theme(plot.title = element_text(hjust = 0.5))更具吸引力,而且记住起来也容易得多。

ggplot(data = dat, aes(time, 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") +
  ggeasy::easy_center_title()

enter image description here

请注意,在撰写此答案时,您将需要从GitHub安装ggeasy的开发版本以使用easy_center_title()。您可以通过运行remotes::install_github("jonocarroll/ggeasy")来实现。

答案 3 :(得分:0)

如果您要处理大量图形和ggplot,则每次添加theme()可能会很累。如果您不想按照前面建议的那样更改默认主题,则可能会发现创建自己的个人主题更加容易。

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

假设您有多个图p1,p2和p3,只需在其中添加personal_theme。

p1 + personal_theme
p2 + personal_theme
p3 + personal_theme

dat <- data.frame(
  time = factor(c("Lunch","Dinner"), 
levels=c("Lunch","Dinner")),
  total_bill = c(14.89, 17.23)
)
p1 = 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")

p1 + personal_theme
相关问题