Center Plot title in ggplot2

Hi this simple code (and all my scripts from this morning) has started giving me a off center title in ggplot2

Ubuntu version: 16.04

R studio version: Version 0.99.896

R version: 3.3.2

GGPLOT2 version: 2.2.0

I have freshly installed the above this morning to try and fix this....

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

在这里输入图像描述


From the release news of ggplot 2.2.0 : "The main plot title is now left-aligned to better work better with a subtitle". See also the plot.title argument in ?theme : "left-aligned by default".

As pointed out by @J_F, you may add theme(plot.title = element_text(hjust = 0.5)) to center the title.

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

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


As stated in the answer by Henrik, titles are left-aligned by default starting with ggplot 2.2.0. Titles can be centered by adding this to the plot:

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

However, if you create many plots, it may be tedious to add this line everywhere. One could then also change the default behaviour of ggplot with

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

Once you have run this line, all plots created afterwards will use the theme setting plot.title = element_text(hjust = 0.5) as their default:

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

To get back to the original ggplot2 default settings you can either restart the R session or choose the default theme with

theme_set(theme_gray())
链接地址: http://www.djcxy.com/p/30852.html

上一篇: 如何为离散值生成有意义的绘图员/关联图

下一篇: 在ggplot2中心绘图标题