Wednesday, March 06, 2013

Visualise your data with D3.js

Recently I've been learning about D3. It's a Javascript library which helps to visualise data. The web app that I'm working on logs usage data when a user performs particular actions.

I've put together a REST interface which returns all the actions for the last few weeks as an array of Javascript objects. Something a little like this:
{"id":111, "time":1362145523957, "userName":"perky", "activity":"change direction"}
Using this data I want to show how many of each activity has been done per day. D3 makes this really simple, the nest function allows me group the data on multiple keys:
var dateFormat = d3.time.format("%x"),
    nestedData = d3.nest()
    .key(function(d) { return d.activity; })
    .key(function(d) {return dateFormat(new Date(d.time));})
    .entries(data);
The nestedData is a tree in which I have a key value pair for each activity and the value is an array of key value pairs for each day in which there are activities of that type.


D3 also provides convenient ways to scale the generated output along each axis. In the SVG that is generated I set the interval along the X axis for each day ranging from the earliest to the last date in my data set. The resulting line graph and the code used to generate it are both available in this jsfiddle.

Mike Bostock, the creator of D3, has some really good examples of what D3 can do on bl.ocks.org/mbostock.

If you want to use D3 for producing graphs it may also be worth looking into NVD3 and Rickshaw which use D3 to but handle some of the hard work for you.

No comments: