20.1 New themes

Themes are probably the easiest form of extensions as they only require you to write code you would normally write when creating plots with ggplot2. While it is possible to build up a new theme from the ground it is usually easier and less error-prone to modify an existing theme. This is done in ggplot2 as well as can be seen by looking at e.g. theme_minimal():

print(theme_minimal)
#> function (base_size = 11, base_family = "", base_line_size = base_size/22, 
#>     base_rect_size = base_size/22) 
#> {
#>     theme_bw(base_size = base_size, base_family = base_family, 
#>         base_line_size = base_line_size, base_rect_size = base_rect_size) %+replace% 
#>         theme(axis.ticks = element_blank(), legend.background = element_blank(), 
#>             legend.key = element_blank(), panel.background = element_blank(), 
#>             panel.border = element_blank(), strip.background = element_blank(), 
#>             plot.background = element_blank(), complete = TRUE)
#> }
#> <bytecode: 0x558485562f08>
#> <environment: namespace:ggplot2>

here the base is theme_bw() and the theme then replaces certain parts of it with its own style using the exported %+replace% operator. As can be seen, the code doesn’t look much different to the code you normally write when styling a plot. While not adviced, it is also possible to create a theme without modifying an existing one. The general approach is to simply use the theme() function while setting complete = TRUE. It is important to make sure that at least all theme elements that do not inherit from other elements have been defined when using this approach. See e.g. theme_gray() for an example of this.

When writing new themes it is a good idea to provide a few parameters to the user for defining overarching aspects of the theme. One important such aspect is sizing of text and lines but other aspects could be e.g. key and accent colours of the theme.

Maybe something about creating new theme elements?