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:
- We’ll start as simple as possible by using the existing
geom_path(), pairing it with a new stat.
- The new stat only allows fixed diameter and tension, so we’ll next allow these to be set as parameters.
- 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.
- 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.
- 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.