Creating a New ggplot2 Theme

Thursday, Feb 8, 2018
R

This post introduces simple steps on how to create your own ggplot2 theme. Of course, it will not go into details of changing all the aspects. Instead, it will highlight the process using few useful elements.

Theme is basically a set of pre-defined(default) values for elements that make up a plot in ggplot2 library. Major elements are:

Default Theme

Instead of rewriting properties of all elements, it is more efficient to pick a theme that is closer to what you want and make some adjustments. In my case, I like the theme_bw so I will use that as a starting point. A scatter plot on this theme looks like this:

theme_set(theme_bw())
ggplot(mpg, aes(displ, hwy)) + geom_point()

New Theme

I like white background and black border of this theme. Few changes I would like to make to this theme are:

To make these changes, we will simply ‘add’ these elements to our base theme:

theme_simple <- function() {
    theme_bw(base_size = 14,
             base_family = "") %+replace%
    theme(panel.grid = element_blank(),
          axis.text = element_text(color = "black"))
}

Notice that I have created a new function for this theme instead of just storing it in an object. This makes it flexible since now it can be sourced in any project and used. Let's see how our plot looks now with the new theme.

theme_set(theme_simple())
ggplot(mpg, aes(displ, hwy)) + geom_point()

It looks more clear now bringing more attention to the data instead of theme or plot elements. You can find what else can be changed by ?theme.

Further Reading

In case you want to dig deeper into the topic of customizing themes, here are some additional resource: