HannesZ HannesZ - 1 year ago 189
R Question

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

Answer Source

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

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download