D3 For People who know Javascript

D3.js is used for displaying all kinds of data visually. Basically its a tool for information visualization with a huge number of methods to help you "see" the information.

D3 is based in Javascript so if you know your javascript you already have a headstart.

Apart from this really quick tutorial I would recommend:

  1. This YouTube series is really worth it.
  2. The API is quite legible.

Basics of D3.

The super basic idea is to manipulate DOM elements based on data. Though since this is possible in jQuery really easily why should we bother with D3.

Simply because D3 was built for the manipulation. D3 contains a whole bunch of methods to produce scales (log and linear scales for example), create polygons (for cool artsy representations), for converting a JSON stream into geo-coordinates etc.

Now though you can manipulate any element one of the simplest and most obvious choices for any manipulation would be the SVG or Canvas element

SVG for manipulation in D3

To add an SVG to the DOM is quite simple

 var canvas = d3.select("body")

This code is quite similar to the jQuery code to add the same.

First bar graph

Now lets try some basic D3 code to create a bar graph. A bar graph is a series of rectangles based on the values provided. So, first lets assume our data is stored in a JSON file data.json like so

{ name: 'x' size :10},
{ name: 'z' size :12},
{ name: 'y' size :4}

Now to make the graph

d3.json("data.json", function (data){
          .attr(width,function(d){ d.size *10})
          .attr(y,function(d,i){ i*55})


What the above code does is:

  1. selects all the DOM elements that are rects (none)
  2. enters a number of rectangles (i.e. the # of data elements - the # of rectangles present)
  3. The width of the rectangle is given by a function of size.
  4. The y position is given by the number (hence a function with 2 parameters)

These are the real basics of D3. Second tutorial on their Time and Geometry Libraries will come after a while

20 Apr 2014