/ Daniel Grady

Learning D3 by building a Cartesian grid plugin

D3 is a JavaScript library that's aimed at helping you make visualizations of data. It makes use of some powerful and challenging ideas, like declarative data binding to produce enter, update, and exit selections, and parity between transitions and selections. Getting started with D3 is quick and easy because of the wealth of examples that Mike Bostock and others have produced, but as I began to work on implementing my own reusable components, I had a hard time understanding how to modify or extend some of the behaviors that have become a hallmark of the library, in particular the axis component.

As you would expect from a graphics library, the axis component (working with the scale component) takes care of automatically placing tick marks and labels, but it also works seamlessly with transitions. When you use a transition to update the scale associated with an axis, the axis and all tick marks on it will smoothly fade and slide into their new positions. You can see an example of this by clicking on the graph at right and watching the white grid lines. This component does something relatively simple but uses all of D3's core ideas, so to improve my own understanding of D3, I built a new component based on d3.svg.axis that draws a Cartesian grid. This was (at least for me) not nearly as straightforward as I figured it would be, and in case anyone else out there is curious about how the axis component works, this annotated source code could be a good entry point. Aside from a detailed and running explanation of what's happening, the grid plugin doesn't handle drawing text or domain paths like the axis component does, so it's a bit simpler.

Although this project was mainly about the learning experience, a grid component can make some kinds of charts simpler to draw. Standard practice for drawing a grid in the D3 community is to use an axis but extend the tick marks to cover the entire chart width; this is exactly what's done in the example above. But if you want to use axes and a grid in the same chart, as shown at right, you have to coordinate the two components yourself, which can become a bit complicated once you start adding transitions. Instead, it's (marginally) nicer to have a separate, explicit component that's linked to the tick marks.

d3.svg.axis is designed to handle linear (continuous), time, and ordinal scales, and the d3.svg.grid component works with all three as well:

The annotated source code is available on Github. Writing this helped me understand D3's transitions, and I hope my explanation helps you too.