How to check if the user has set a global ggplot theme with theme_set() or not?

Is it possible to check if the user has set a global ggplot theme with theme_set() or if she is still using the default ggplot theme? If so, how?

This is relevant when one wants to create a function that returns a ggplot with a custom theme, but only if the user has not set her own theme with theme_set().

The idea is:

func <- function() {

  p <- mtcars %>% 
    ggplot() +
    aes(x = wt, y = mpg) +
    geom_point()
  
  if (user has not set own ggplot theme) {
    p <- p + theme_custom()
    return(p)
  } else {
    return(p)
  }
}

The most elegant solution would be if there was a check_theme_set() function that returns TRUE if the user has set her own theme with theme_set() and FALSE if the user is still using the default ggplot theme.

(FYI, this question is inspired by: ggplot2::theme_set() doesn't work with plot_cap() and plot_cme() · Issue #212 · vincentarelbundock/marginaleffects · GitHub)

Hi @Captain,

{ggplot2} uses an internal object ggplot_global to keep track of global settings (like theme). A theme is set by default when ggplot2 is loaded, so using something like theme_get() will always return a ggplot2 theme whether or not the user has set their own preferred theme or not.

A workaround might be to check whether the user has changed from the default theme and if not, then you use your custom theme:

library(ggplot2)

is_theme_default <- function() {
  comparison <- all.equal(ggplot2::theme_get(), ggplot2::theme_gray())
  if (is.logical(comparison) & isTRUE(comparison)) return(TRUE)
  FALSE
}

is_theme_default()
#> [1] TRUE

theme_set(theme_minimal())

is_theme_default()
#> [1] FALSE

Hope this is helpful.

1 Like

Hi @mattwarkentin,

Thanks for your reply!

I got as far as you did, using a function to check if the user is using theme_grey() (the ggplot default) or not, and if so, changing it to theme_minimal(). This works as a workaround for all users who have used theme_set() with a theme other than theme_grey(). For those users, the function produces the ggplot in their preferred theme. For users who didn't set a theme, the plot will be produced with theme_minimal(). However, some of the users who didn't set a theme actually will want their plots in theme_grey() and they no longer have the option to use theme_set(theme_grey()) to set the theme for their plots globally, they will need to use + theme_grey() with every plot they produce, which is not ideal.

func <- function() {
  
  p <- mtcars %>% 
    ggplot() +
    aes(x = wt, y = mpg) +
    geom_point()
  
  if (identical(theme_get(), theme_grey())) {
    p <- p + ggplot2::theme_minimal()
    return(p)
  } else {
    return(p)
  }
}

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.