Skip to content

Instantly share code, notes, and snippets.

@sfirke
Last active September 21, 2017 18:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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