25
votes

I created a package with plenty of functions that generate ggplot plots.

At the beginning, I used the default theme for all my plot functions (grey theme) but then I found the black and white theme to be more pleasant to the eye and developed my latest plot functions using that theme.

Is there a way to set the ggplot2 theme globally, i.e. in one place, without having to modify all my plot functions each time I find a new theme I want to apply to all my plots?

3
there is theme_setuser20650
?theme_set / ?theme_update / ?theme_replace (they all point to the same manual page)hrbrmstr

3 Answers

72
votes

here you go, you should attach the package again

 library(ggplot2); theme_set(theme_bw())
13
votes

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
6
votes

There is now an R-package to set themes globally. https://rstudio.github.io/thematic/

Their example code:

library(thematic)
thematic_on(
  bg = "#222222", fg = "white", accent = "#0CE3AC",
  font = font_spec("Oxanium", scale = 1.25)
)

After that, each plot inherits these settings.