0 to d3 in 10 minutes or less
At its core, D3 is a framework that converts data into HTML/SVG elements. In order to accomplish this, we need to provide the following three functions.
- what happens when a new data element is inserted
- what happens when a piece of data is changed
- what happens when data is deleted
Let’s take these three concepts one at a time.
We will be using the following dataset for illustration purposes:
Basically, the function generates a array of 10 numbers between 0 and 100.
This is the first step where we bind data to DOM elements. First we use
d3.select to select all the element we want to modify, then bind the data via
d3.data. Finally, we define the enter (aka what happens when new data is added) behaviour.
So in this particular case, when we encounter a new data element, we want to set the width to be the value of the data, set height to be 10px, and the background color to be
Putting it all together:
and it looks like this:
How data changes
This part is easy, when the data changes (already is inserted), then we just want to modify the width.
Wrapping the whole thing (before
var data = ... to just after last line) in a
setInterval, we can see the bars are dancing happily below:
How we remove data
The final part of the D3 trio of fundamental function is the
.exit (corresponds to
Simply removing the element that has exited is very simple, the following code should suffice:
With some flourishes through the magic of
.transition, we can make the exiting element animate and making it more obvious.
The finished example is below:
The following execellent articles should cover various aspects of D3 in significant more depth than I can, and should be a must read if you want to really understand how D3 works.
Mike Bostock, who is the createor of d3, also happen to be a great teacher; He has kindly created a few wonderfully illustrative tutorials on various aspects of D3 that freqently trips up new comers:
- Three little circles, an illustration of what we just talked about with three little circles
- How selections work, a deeper dive into various ways d3 allow you to select what you want
- Thinking with Joins, a further article on how to reason about d3 program through the three enter/update/exit pattern
- How to update, diving deep into how to manage state transition from one state to another and conform to user’s expectations
- Object Constancy, how to keep the same object constant through updates
That’s it for today! If you want some inspirations, hit D3 Gallery for some amazing visulizations that will keep you entertained for hours.