Themes (ggplot)

Quick Intro

Themes and theme elements control the non-data components of the plot. The use, of predefined themes and custom themes in ggplot are described below.  

ggplot provides two built-in format themes.  theme_grey() is the default theme and has a grey plot background.  theme_bw() is a simple black and white theme.  ggplot also provides functions to modify theme elements or to create new themes.

Switching between themes is as simple as adding the theme layer to the plot.    

Plot128Plot129

Basic Theme Commands

At startup, ggplot sources and sets the default function theme_grey().  The function argument base_size is a scalar to control relative font size for different text across across the plot.  The  base_family argument is used to define font choice.

The formatting of specific theme elements is controlled with the theme() function.  These one-time format changes apply to the current call to the graphical device only.  You can change the current theme with the theme_update() or the %+replace% operator to ensure format changes are applied across multiple calls to the graphical device.  Finally, you can load alternative themes to replace the current theme with theme.set().  theme_set() will only work if the theme function being called has been sourced and is available in memory.

theme_grey()

Every theme is a function with multiple theme elements set to format options.  The ggplot source code for the default theme is displayed below.

theme_bw()

theme_bw() is a derivative of the theme_grey().  The source code function definition does not explicitly define format options for all theme elements.  Instead, it relies on the %+replace% operator to update only a few theme elements.  All other theme elements have been set by theme_grey() function.

Custom Themes

The following function illustrates how to create a custom theme function theme_blue().  The function redefines theme element formats explicitly (and does not use %+replace%).  Source the function into memory and replace the default theme using theme_set(theme_blue()).

Plot130b

Leave a Reply