Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (7.3k points)
edited by

Hi this simple code (and all my scripts from this morning) has started giving me an 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")

enter image description here

1 Answer

0 votes
by
edited by

By default, the plot titles in ggplot2 are left aligned. To set the titles to center, you need to adjust the horizontal justification with the hjust function and add the following layer to your plot:

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

Adding this line of code to your plot will set the title to the center for all the plots created afterward:

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

Browse Categories

...