D3.js Step by Step: Intro
Some background on D3.js and an overview of this series
UPDATE (July 18, 2016): The code and API links in these tutorials have been updated to target D3 v4, which was a complete rewrite. The D3 wiki contains a breakdown of the changes from v3.
TL;DR
This post is part of a series that explores some key concepts in D3.js by building up an example, step by step, from a bare-bones pie chart to an interactive, animated donut chart that loads external data. For the enough-with-the-jibber-jabber-show-me-the-code types out there, here's a breakdown of the steps we'll be covering:
- Step 0: Intro ← You Are Here
- Step 1: A Basic Pie Chart (Code | Demo)
- Step 2: A Basic Donut Chart (Code | Demo)
- Step 3: Adding a Legend (Code | Demo)
- Step 4: Loading External Data (Code | Demo)
- Step 5: Adding Tooltips (Code | Demo)
- Step 6: Animating Interactivity (Code | Demo)
NOTE: Because we're building things up step by step, the source code contains NEW
, UPDATED
and REMOVED
comments to annotate the lines that have been added, altered or deleted relative to the previous step.
D3.js, in case you are unfamiliar with it, is a powerful and flexible JavaScript library that can be used to create interactive data visualizations with HTML, SVG and CSS. D3 stands for Data-Driven Documents and it's behind some of the most innovative and engaging visualizations currently on the web. On d3js.org you can find a wide variety of examples in addition to extensive documentation. I think it's one of the most exciting projects in the JavaScript ecosystem, and its prolific creator, Mike Bostock, deserves our collective thanks and admiration.
As great as it is, even experienced JavaScript developers can find D3 daunting at first. It seems like a lot of code is needed to do anything at all and there is so much available in the D3 namespace. That, however, is simply a byproduct of how flexible it is. The key is to keep calm and take it one step at a time. By looking at each small piece on its own and seeing how it fits with the rest of the puzzle, you'll find that patterns start to emerge and that it's not so daunting after all.
We'll start with this bare-bones pie chart:
And by the end we'll have this interactive, animated donut chart that loads data from an external source. Try clicking on the coloured squares in the legend to filter the dataset:
We're going to be covering a lot of ground in these posts, so we'd better get started... onwards to Step 1: A Basic Pie Chart.