Saturday, September 6, 2014

Getting started with D3.js

With support for SVG and Canvas being in all major browsers for a while now, HTML is not the only way to display content anymore in a browser. If data-driven graphics are your thing, it might be time to take a look at D3.js.

First created in 2011, D3 was designed to provide a perfomant library to create visualizations for data. Since that time, it's grown into one of the most popular visualization frameworks of all time. Large websites such as the New York Times and the Guardian use it frequently when providing data visualizations to news stories. Much of the appeal is the speed and performance that D3 brings to the table.

To get started with D3, you can simply visit their website, http://d3js.org/, or install through bower with bower install d3. Documentation is also available at https://github.com/mbostock/d3/wiki/API-Reference. However, the best way I've found to start using D3 is to look up their huge library of examples. There are two main sites that provide D3 visualization examples (http://bl.ocks.org/mbostock and https://github.com/mbostock/d3/wiki/Gallery), and both have hundreds of graph types to choose from. My favorite example to start with is called "The Amazing Pie", and available at http://bl.ocks.org/mbostock/4341574

D3 has a similar syntax to jQuery, with d3.select() being the $() equivalent. Unfortunately it is very low level, so it is necessary to have a basic understanding of SVG drawing to create visualizations. Luckily, SVG is similar to HTML, but with different, vector-based tags, such as <arc>, <text>, and <path>. It's usually easiest to then position elements by giving them a width, height, and style="transform: translate(x,y)". Just like HTML, SVG elements can use styles and classes, but the SVG version of css is, again, slightly different. For more information about SVG elements, I recommend Mozilla's SVG documentation at https://developer.mozilla.org/en-US/docs/Web/SVG/Element.

SVGs also support events and interactivity. A good example of using D3 to add interactivity can be found at http://bl.ocks.org/Caged/6476579, which shows how to implement a tooltip.

These examples barely scratch the surface of what D3 is capable of. To learn more, I'd suggest finding examples that look interesting, and experimenting from there.