d3.js
More than 1 year has passed since last update.


D3.js

D3, which stands for Data Driven Documents, is a JavaScript library which allows to bind HTML elements to some data. It is therefore well-suited to create charts, and more generally speaking data visualisation related content.


Selection

D3 selects DOM elements using CSS3 syntax. For instance, this select a paragraph with the bodyId id and the paragraphClass class:

var selection = d3.select("p #bodyId .paragraphClass");

Then, D3 can perform various actions on this selection, for instance this is how to add a div into the DOM element:

selection.append("div");


Binding data

This is the core functionality of the library. Let's say we have this array of data

var arrayOfData = [2, 4, 9, 10];

and we want to use it to create circles which size depends on the number.

First, we need to create an SVG element in which the circles will be drawn.

var svg = d3.select("body").append("svg")

.attr("width", 800)
.attr("height", 400);

Then, we can select the circles even though they haven't been created yet, and bind the data to them.

var svg = d3.select("body").append("svg")

.attr("width", 800)
.attr("height", 400);

The enter function is used to create placeholders nodes to the data that hasn't been bound yet. This piece of code

circles.enter()

.append("circle")

creates a circle for each element of the array, as no circle exists yet.

The next step is to actually use the data. This can be done anytime by replacing a constant by such an anonymous function

function(d, i) {

...
}

where d represents the associated data element, and i the index. We can use d to calculate the size, and i for the offset:

circles.enter()

.append("circle")
.attr({
"cx": function(d, i) {
return 10 + 100 * i;
},
"cy": 50,
"r" : function(d, i) {
return 2 * d;
}
});

Here is the final result.


Transition

D3 has a nice support for transitions. Basically one just needs to call the transition function. Below is atransition function for the previous example.

function updateCircles() {

var newArrayOfData = [];

for(var i = 0 ; i < 4 ; ++i) {
newArrayOfData[i] = 10 * Math.random();
}
circles
.data(newArrayOfData)
.transition()
.attr("r", function(d) {
return 2 * d;
});
}

See full example here.