Treemap

Treemap design invented by Ben Shneiderman. Squarified algorithm by Bruls, Huizing and van Wijk. Data courtesy Jeff Heer.

Source Code

 1 var w = 960,
 2     h = 500,
 3     color = d3.scale.category20c();
 4 
 5 var treemap = d3.layout.treemap()
 6     .size([w, h])
 7     .sticky(true)
 8     .value(function(d) { return d.size; });
 9 
10 var div = d3.select("#chart").append("div")
11     .style("position", "relative")
12     .style("width", w + "px")
13     .style("height", h + "px");
14 
15 d3.json("../data/flare.json", function(json) {
16   div.data([json]).selectAll("div")
17       .data(treemap.nodes)
18     .enter().append("div")
19       .attr("class", "cell")
20       .style("background", function(d) { return d.children ? color(d.name) : null; })
21       .call(cell)
22       .text(function(d) { return d.children ? null : d.name; });
23 
24   d3.select("#size").on("click", function() {
25     div.selectAll("div")
26         .data(treemap.value(function(d) { return d.size; }))
27       .transition()
28         .duration(1500)
29         .call(cell);
30 
31     d3.select("#size").classed("active", true);
32     d3.select("#count").classed("active", false);
33   });
34 
35   d3.select("#count").on("click", function() {
36     div.selectAll("div")
37         .data(treemap.value(function(d) { return 1; }))
38       .transition()
39         .duration(1500)
40         .call(cell);
41 
42     d3.select("#size").classed("active", false);
43     d3.select("#count").classed("active", true);
44   });
45 });
46 
47 function cell() {
48   this
49       .style("left", function(d) { return d.x + "px"; })
50       .style("top", function(d) { return d.y + "px"; })
51       .style("width", function(d) { return d.dx - 1 + "px"; })
52       .style("height", function(d) { return d.dy - 1 + "px"; });
53 }
Copyright © 2011 Mike Bostock
Fork me on GitHub