18.1 Introduction

A major requirement of a good data analysis is flexibility. If your data changes, or you discover something that makes you rethink your basic assumptions, you need to be able to easily change many plots at once. The main inhibitor of flexibility is code duplication. If you have the same plotting statement repeated over and over again, you’ll have to make the same change in many different places. Often just the thought of making all those changes is exhausting! This chapter will help you overcome that problem by showing you how to program with ggplot2.

To make your code more flexible, you need to reduce duplicated code by writing functions. When you notice you’re doing the same thing over and over again, think about how you might generalise it and turn it into a function. If you’re not that familiar with how functions work in R, you might want to brush up your knowledge at http://adv-r.had.co.nz/Functions.html.

In this chapter I’ll show how to write functions that create:

  • A single ggplot2 component.
  • Multiple ggplot2 components.
  • A complete plot.

And then I’ll finish off with a brief illustration of how you can apply functional programming techniques to ggplot2 objects.

You might also find the cowplot and ggthemes packages helpful. As well as providing reusable components that help you directly, you can also read the source code of the packages to figure out how they work.