by Peter Cook / @prcweb / www.prcweb.co.uk
D3.js is a JavaScript library for (facilitating) data visualisation in the browser (mostly)
CSV data bound to SVG elements
Layouts, transitions
Energy data bound to SVG elements, events
GeoJSON, projection, events
SVG, paths, interaction
Similar to, but not the same as, jQuery
/* jQuery */
$('td'); //Returns array (wrapped set) of elements
/* D3 */
d3.select('table'); //Returns array of arrays [[<table>]]
d3.selectAll('td'); //[[<td>, <td>, <td>, <td>]]
d3.selectAll('tr').selectAll('td'); //[[<td>, <td>], [<td>, <td>]]
d3.selectAll('td').text('Some data');
/* Data */
var d = [6, 1, 4, 2, 5];
/* Selection */
var selection = d3.selectAll('li');
/* Bind data to elements */
var updateSelection = selection.data(d);
updateSelection[0][0].__data__; // 6
updateSelection.text(function(d) {return d;});
/* Transitions */
d3.select('p').transition().style('font-size', '40px')
/* Arrays */
a = [4, 1, 2, 6, 10]
d3.extent(a) //returns [1, 10]
d3.permute(['a', 'b', 'c'], [1, 2, 0]) //returns ['b', 'c', 'a']
/* Requests - similar to jQuery.get() etc. */
/* Formatting */
var zero = d3.format("04d")
zero(2) // returns '0002'
/* Colours */
var red = d3.rgb('red')
red.r // 255
red.g // 0
var darkerRed = red.darker()
darker.r // 178
d3.select('p').style('color', darkerRed)
Scales are functions that map from an input domain to an output range
var s = d3.scale.linear().domain([0, 1]).range([-10, 10])
s(0) // -10
s(0.5) // 0
var cs = d3.scale.linear().domain([0, 1]).range(['white', 'red'])
cs(0) // '#ffffff'
cs(1) // '#ff0000'
Add SVG elements like any other element
d3.select('svg').append('circle')
.attr('cx', 40).attr('cy', 40).attr('r', 40)
.style('fill', 'red');
...or use an SVG generator to generate path data
/* Create SVG path data generator */
var line = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; });
/* Data */
var d = [{x: 10, y:10}, {x:20, y:30}, {x:30, y:20}];
/* Generate path data */
line(d); // "M10,10L20,30L30,20"
line.interpolate('basis');
pathData = line(d); // "M10,10C10,10,10,10,11.666,13.333C13.333..."
/* Add to the DOM */
d3.select('svg').append('path').attr('d', pathData);
//Other generators include arc, symbol, chord, diagonal
/* Time scales */
first = new Date('1 Jan 2013');
last = new Date('31 Dec 2013');
var ts = d3.time.scale().domain([first, last]).range([0,1]);
ts(new Date('10 Jan 2013')); // 0.0247
/* Time intervals */
d3.time.week(new Date('4 Jan 2013')); // Sun Dec 30 2012 00:00:00
/* Counting */
d3.time.dayOfYear('10 Jan 2013'); // 9
Maps geographic data (GeoJSON) to SVG path data
Many, many different projections
(Mercator, Albers, Gringorten... many more)
Peter Cook / @prcweb / www.prcweb.co.uk