elliot
elliot

Reputation: 1944

How to add extra arguments to ggplot2 theme?

I'd like to create a script specific theme for some ggplots I'm producing. I plan to have a set custom theme that allows me to make some adjustments if needed using the three-dot notation .... Something like this.

theme_script <- theme(text = element_text(color = 'black'), 
        panel.background = element_blank(), 
        axis.line.x = element_line(color = 'black'), 
        axis.ticks = element_blank(), 
        plot.margin = margin(.5, .5, .5, .5, 'cm'), ...) # dot notation

Then I could use thescript_theme for things like.

plot + 
theme_script(text = element_text(size = 25))

But I'm getting this message Error: '...' used in an incorrect context. Is there a better approach to accomplishing my goal?

Upvotes: 2

Views: 513

Answers (1)

Claus Wilke
Claus Wilke

Reputation: 17790

If you want to be able to set arbitrary elements, including ones that are already set in your default theme, then you need to use theme addition inside your function, as shown in the following example.

library(ggplot2) 

theme_script <- function(...) {
  theme(
    text = element_text(color = 'black'), 
    panel.background = element_blank(), 
    axis.line.x = element_line(color = 'black'), 
    axis.ticks = element_blank(), 
    plot.margin = margin(.5, .5, .5, .5, 'cm')
  ) +
    theme(...)
}

ggplot(mtcars, aes(disp, mpg)) + geom_point() +
  theme_script(text = element_text(size = 25))

Created on 2020-01-01 by the reprex package (v0.3.0)

Upvotes: 2

Related Questions