How to set themes globally for ggplot2?

What I do is to set

th <- theme()

at the top of my script and then include this to all ggplots. It needs to be added before any plot specific themes or it will overwrite them.

df <- data.frame(x = rnorm(100))
ggplot(df, aes(x = x)) +
  geom_histogram() + 
  th +
  theme(panel.grid.major = element_line(colour = "pink"))

At a later stage, you can then change th to a different theme

Edit

theme_set and related functions theme_replace and theme_update suggested by hrbrmstr in the comments are probably better solutions to this problem. They don't require existing code to be edited.

g <- ggplot(df, aes(x = x)) +
  geom_histogram() + 

g
old <- theme_set(theme_bw()) #capture current theme
g
theme_set(old) #reset theme to previous

here you go, you should attach the package again

 library(ggplot2); theme_set(theme_bw())

Tags:

R

Ggplot2