The default alignment is for a ggplot title to be left-aligned to the plot.background element. Others have noted that you can use plot.title = element_text(hjust = 0.5)
to center the title.
However, I want to center the title across the entire panel as oppose to just the plot. I have done this in the past by modifying the hjust
to push the title so that it appears centered, but value of hjust
is dependent on the length of the title which makes it really tedious to set when I'm batch-producing graphs.
Is it possible to consistently set the title elements of a ggplot to be centered across the panel.background?
library(reprex)
library(tidyverse)
data(mtcars)
mtcars %>%
rownames_to_column(var = "model") %>%
top_n(8,wt) %>%
ggplot(aes(x =model, y = wt))+
geom_col()+
coord_flip()+
labs(title="This title is left-aligned to the plot")
mtcars %>%
rownames_to_column(var = "model") %>%
top_n(8,wt) %>%
ggplot(aes(x =model, y = wt))+
geom_col()+
coord_flip()+
labs(title="This title is center-aligned to the plot width.")+
theme(plot.title = element_text(hjust = 0.5))
mtcars %>%
rownames_to_column(var = "model") %>%
top_n(8,wt) %>%
ggplot(aes(x =model, y = wt))+
geom_col()+
coord_flip()+
labs(title="Short title, still works")+
theme(plot.title = element_text(hjust = 0.5))
mtcars %>%
rownames_to_column(var = "model") %>%
top_n(8,wt) %>%
ggplot(aes(x =model, y = wt))+
geom_col()+
coord_flip()+
labs(title="This title is roughly center-aligned to panel")+
theme(plot.title = element_text(hjust = 0.37)) # I know I can adjust this, but it would require a manual fix each time
Suggestion by @user20650
p <- mtcars %>%
rownames_to_column(var = "model") %>%
top_n(8,wt) %>%
ggplot(aes(x =model, y = wt))+
geom_col()+
coord_flip()+
#labs(title="Short title, still works")+
theme(plot.title = element_text(hjust = 0.5))
gridExtra::grid.arrange( top=grid::textGrob("This title is center-aligned to panel"),p )
Created on 2018-09-24 by the reprex package (v0.2.1)