How to center ggplot plot title
Short solution I've found:
theme(plot.title = element_text(hjust = -0.2))
hjust parameter controls distance from the left alignment to the y axis. Negative values move text to the left
Alternately, you can use gridExtra::grid.arrange
and grid::textGrob
to create the title without needing to pad it visually. This basically creates a separate plot object with your title and glues it on top, independing of the contents of your ggplot
call.
First store your whole ggplot
call in a variable, e.g. p1
:
grid.arrange(textGrob("Mary Poppins",
gp = gpar(fontsize = 2.5*11, fontface = "bold")),
p1,
heights = c(0.1, 1))
You have to translate your theme()
settings to gpar()
. The base size of theme_light
is 11, which is where the 2.5*11 comes from (and the 2.5 from your rel(2.5)
).
The advantage here is that you know your title will be truly centered, not just close enough by eye.
Solution adding white space to centre title:
Add spaces after the title with:
ggtitle(paste0("Mary Poppins", paste0(rep("", 30), collapse = " ")))
For the output like this:
Not perfect solution, but works.