Center Plot Title In Ggplot2
Answer :
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())
The ggeasy
package has a function called easy_center_title()
to do just that. I find it much more appealing than theme(plot.title = element_text(hjust = 0.5))
and it's so much easier to remember.
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()
Note that as of writing this answer you will need to install the development version of ggeasy
from GitHub to use easy_center_title()
. You can do so by running remotes::install_github("jonocarroll/ggeasy")
.
Comments
Post a Comment