21 Case Study: Springs

To make the ideas in the previous chapter concrete, here we’ll work through the process of building a new geom that looks like a spring. This is a carefully crafted example: you’re unlikely to actually want to use springs to visualise your data (so no geom already exists), and they’re just complicated enough to illustrate the most important parts of the process.

We’ll development the extension in five phases:

  1. We’ll start as simple as possible by using the existing geom_path(), pairing it with a new stat.
  2. The new stat only allows fixed diameter and tension, so we’ll next allow these to be set as parameters.
  3. A stat is a great place to start but has some fundamental restrictions so we’ll convert our work so far in to a proper geom.
  4. Geoms can only use dimensions relative to the data, and can’t use absolute sizes like 2cm, so next we’ll show you how to draw the spring with grid.
  5. We’ll finish up by providing a custom scale and legend to pair with the geom.

Once you’ve worked your way through this chapter, I highly recommend browsing the ggplot2 source code to look at how other stats and geoms are implemented. They will often be more complicated than what you need, but they’ll give you a sense of the things you can do.