This book has been using
theme_classic() for the plots, because the default grey background can make certain colours harder to see.
But, like every other part of the grammar of graphics, we can modify the theme of the plot to suit our needs, or higher sense of style!
There are way too many theme elements built into the
ggplot2 package to mention here, but you can find a complete list in the theme vignette. Instead of
modifying the many elements contained in
theme(), you can start from theme functions, which contain a specific set of elements from which to start. Here are some examples:
As you may have noticed,
ggplot code can quickly become long when you constantly need to specify the characteristics of the theme you want to use. When you are making multiple plots and want them to all have the same theme, you can simple use
theme_set() to set the theme for all plots that are generated afterwards, or
theme_update() to edit elements of an existing theme setting without rewriting all the other theme elements.
pp plot is generated with the black & white theme
theme_bw(). Any future plots generated in your R session would also be generated with this theme.
Perhaps the minor gridlines are not necessary for this plot, though we like everything else about our theme. Rather than rewriting several lines of code to respecify the theme, we can simply use
theme_update() to adjust a specific element of our theme.
There! Much better!
Here is a helpful infographic to help you customize your theme to fit your exact needs!
Once you become more comfortable with customizing existing ggplot themes, you might want to think about creating your own theme to add to your plots. This is a great way to make your plots stand out in a presentation, a publication, a website, or wherever else they find a home!
Here is an example:
The ggthemes package is a great project developed by Jeffrey Arnold on GitHub and also hosted on the CRAN repository. The package contains many themes, geoms, and colour ramps for
ggplot2 which are based on the works of some of the most renown and influential names in the world of data visualization, from the classics such as Edward Tufte to the modern data journalists and programmers at FiveThirtyEight blog.
The package can be installed as follows:
We can then apply some of these themes (and more) to our plot!