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.
{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:
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)
}
}