38

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?

2
  • 2
    there is theme_set
    – user20650
    Jan 18, 2017 at 11:06
  • 5
    ?theme_set / ?theme_update / ?theme_replace (they all point to the same manual page)
    – hrbrmstr
    Jan 18, 2017 at 11:06

3 Answers 3

87

here you go, you should attach the package again

 library(ggplot2); theme_set(theme_bw())
1
  • 1
    How to add custom settings though, such as panel.background = element_rect(fill = "#f2f2f2ff",colour = NA)
    – jzadra
    Jun 28, 2020 at 17:35
20

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
4
  • 6
    you might want to just use theme_set
    – hrbrmstr
    Jan 18, 2017 at 11:07
  • Whhat if you want the panel.grid.major to be part of the theme as an addition to, say, theme_grey()?
    – jzadra
    Jun 28, 2020 at 17:36
  • 4
    @jzadra theme_set(theme_bw() + theme(panel.grid.major = element_line(colour = "blue"))) Jun 28, 2020 at 20:17
  • Thank you @RichardTelford for the tip. I think this was the best way to do it.
    – Afshin
    Jan 5 at 8:58
10

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.