A couple weeks ago, Protovis, a visualization library I’d been using was deprecated in favor of D3 and I thought I’d share some of the work I’d done porting visualizations from the old to the new.
One example that Protovis has for which there is no corresponding tutorial is sparklines. This sparkline shows the San Diego Padres’ first 100 games of the 2011 season. Up ticks are wins and down ticks are losses. Red ticks show shutouts. This is similar to the visualization in Tufte’s “Beautiful Evidence” p. 54.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
d3.json("padres.json", function(json) { var h = 16, w = json.length * 2; var svg = d3.select("#sparktick") .append("svg:svg") .attr("height", h) .attr("width", w); var node = svg.selectAll("g.tick") .data(json) .enter().append("svg:g") .attr("class", "tick"); node.append("svg:rect") .attr("class", function(d) { return d['RF'] == 0 || d['RA'] == 0?"shutout":"normal"; }) .attr("x", function(d, i) { return i * 2 + 1; }) .attr("y", function(d) { return d['RF'] > d['RA']?0:h/2; }) .attr("height", h/2) .attr("width", 1); node.append("svg:title") .text(function (d) { return d['Team'] + " (" + d['RF'] + ") " + (d['Away']?"vs":"@") + " " + d['Opp'] + " (" + d['RA'] + ") on " + d['Date']; }) }); |
I created another simple visualization for the National League West. This shows all five teams of the NL West on a single graphic. It is pretty easy to adapt this code to a single sparkline. So far I have been fairly pleased with D3’s performance and the ease of use.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
d3.json("nlwest.json", function(json) { // calculate max and min values in the NLWest data var max=0, min=0, len=0; for(var team in json) { min = d3.min([d3.min(json[team]), min]); max = d3.max([d3.max(json[team]), max]); len = d3.max([json[team].length, len]); } var h = 50, w = 250, p = 2, fill = d3.scale.category10() x = d3.scale.linear().domain([0, len]).range([p, w - p]), y = d3.scale.linear().domain([min, max]).range([h - p, p]), line = d3.svg.line() .x(function(d, i) { return x(i); }) .y(function(d) { return y(d); }); var svg = d3.select("#sparkline") .append("svg:svg") .attr("height", h) .attr("width", w); for(var team in json) { var g = svg.append("svg:g"); g.append("svg:path") .attr("d", line(json[team])) .attr("stroke", function(d) { return fill(team); }) .attr("class", "team"); g.append("svg:title") .text(team); } }); |
This is great, thanks for sharing this. I’m about to make the transition away from protovis, this saves me from reinventing the sparkline wheel!
[…] sparklines in d3 […]