Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a custom theme that can inherit theme parameters

I wish to create a custom theme function, which can inherit all the arguments from theme.

So far, I have something like:

my_theme <- function(...){
  theme(axis.title = element_text(colour = "red"))
}

If I want to change the plot background for example, I currently need to do:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ggplot(iris,
       aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  my_theme() +
  theme(panel.background = element_rect(fill = "blue",
                                        colour = "green"))

While I wish I could do:

ggplot(iris,
       aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  my_theme(panel.background = element_rect(fill = "blue",
                                        colour = "green"))

I guess I have to initialize all the theme’s arguments inside the custom function, but is there another work around? Thanks!

>Solution :

You could just pass on the ellipses to theme()?

library(ggplot2)

my_theme <- function(..., axis.title = NULL) {
  axis.title <- if (is.null(axis.title)) {
    element_text(colour = "red") 
  } else {
    axis.title
  } 
  theme(axis.title = axis.title, ...)
}

# Alternatively
my_theme <- function(..., axis.title = element_text(colour = "red")) {
  theme(axis.title = axis.title, ...)
}

ggplot(iris,
       aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  my_theme(panel.background = element_rect(fill = "blue",
                                           colour = "green"))

Created on 2022-02-09 by the reprex package (v2.0.1)

Another option if you’re writing scripts/notebooks for yourself with no intention to package up your code is to just use theme_set() at the beginning, which propagates to all subsequent plots. This is how most of my scripts start.

library(ggplot2)

theme_set(theme_get() + theme(axis.title = element_text(colour = "red")))

ggplot(iris,
       aes(x = Species, y = Sepal.Length)) +
  geom_boxplot() +
  theme(panel.background = element_rect(fill = "blue",
                                        colour = "green"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading