Skip to content

Instantly share code, notes, and snippets.

@sfirke
Last active November 8, 2024 19:43
Show Gist options
  • Save sfirke/130c7ce639526f8bf107c8a066856678 to your computer and use it in GitHub Desktop.
Save sfirke/130c7ce639526f8bf107c8a066856678 to your computer and use it in GitHub Desktop.
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