Last active
November 8, 2024 19:43
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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