Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Center all of your ggplot2 titles over the whole plot using a function
library(ggplot2)
library(dplyr)
library(grid)
library(gridExtra)
add_centered_title <- function(p, text, font_size){
title.grob <- textGrob(
label = text,
gp = gpar(fontsize = font_size,
fontfamily = "Arial")
)
p1 <- arrangeGrob(p, top = title.grob)
grid.arrange(p1)
}
# Create chart that needs a centered title
car_count <- ggplot(mtcars %>%
mutate(am = ifelse(am == 0, "Manual", "Automatic Transmission")),
aes(x = am)) +
geom_bar() +
coord_flip()
# Default, not desired behavior:
car_count +
labs(title = "I want this title to be centered in the page of my report")
# Desired:
add_centered_title(car_count, "I want this title to be centered in the page of my report", 10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment