Replace one ggplot default theme element with an element from another default theme

Viewed 1528

I really like everything about ggplot2's ggtheme's theme_fivethirtyeight() except for the fact that it hides all axis titles.

How can I use theme_fivethirtyeight() but tell it to inherit the axis title specification from another theme?

3 Answers
ggplot_merge_styles <- function(theme, ...) {
  elements <- lapply(as.list(match.call())[-1], function(x) eval(parse(text=deparse(x))))
  for (element in names(elements)) {
    if (element != 'theme') {
      theme[[element]] <- elements[[element]]
    }
  }
  
  return(theme)
}

Then you can specify certain design attributes and merge them together with other styles.

For instance, I enjoy the theme_minimal()'s design on plot.title, except that I want it to be coloured gray instead of it's ordinary black. Then by running the following code, all plot.title properties are preserved except for colour which is being replaced:

plot <- 
  ... +
  theme(plot.title = ggplot_merge_styles(theme_minimal()[['plot.title']], colour = "#6f7170"))
Related