Working with joins in d3.js

D3.js is a well known JavaScript library for creating charts and other visuals using HTML, SVG and CSS. At first you may feel over-whelmed by looking at the features it has to provide. But as you start using it, everything will sink in. The main key behind understanding d3 is the how that data is related to DOM nodes, which is known as joins.

Understanding Joins

Let us assume that we have selected some DOM nodes using one of the select methods provided by d3 and stored it in a variable selection. Now we can assign data to selection by selection.data(data).

Suppose we have n points in our data but there are less than n DOM nodes, extra nodes can be created by selection.enter(). Note that these nodes will be empty.

On other hand if there are greater than n DOM nodes, extra nodes are returned by selection.exit().

The philosophy behind this is Instead of telling D3 how to do something, tell D3 what you want.

So general d3 script will look something like this:

var selection = d3.selecAll("circle");

selection.data(data);

selection.exit().remove();

selection.enter().append('circle') //....and so on

For illustartive example, you can have look at this post by Mike Bostock, the creator of D3.js.

Leave a Reply