简体   繁体   中英

Center Plot title in ggplot2 using theme_bw

Titles are left-aligned by default starting with ggplot 2.2.0. To make them centered again has already been explained in this post:

Center Plot title in ggplot2

This works perfectly in my case as well, however not if I use theme_bw.

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

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")+
  theme(plot.title = element_text(hjust = 0.5))+
  theme_bw()

I tried passing the theme arguments to theme_bw()

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

but that did`t work either.

Any ideas? Help is much appreciated

You just need to invert theme_bw and theme

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") +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5))

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM