Node-Link Tree

Implementation based on work by Jeff Heer and Jason Davies using Buchheim et al.’s linear-time variant of the Reingold-Tilford algorithm. Data shows the Flare class hierarchy, also courtesy Jeff Heer.

Source Code

 1 var r = 960 / 2;
 2 
 3 var tree = d3.layout.tree()
 4     .size([360, r - 120])
 5     .sort(null)
 6     .children(function(d) { return isNaN(d.value) ? d3.entries(d.value) : null; })
 7     .separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
 8 
 9 var diagonal = d3.svg.diagonal()
10     .projection(function(d) {
11       var r = d.y, a = (d.x - 90) / 180 * Math.PI;
12       return [r * Math.cos(a), r * Math.sin(a)];
13     });
14 
15 var vis = d3.select("#chart").append("svg:svg")
16     .attr("width", r * 2)
17     .attr("height", r * 2 - 150)
18   .append("svg:g")
19     .attr("transform", "translate(" + r + "," + r + ")");
20 
21 d3.json("flare.json", function(json) {
22   var nodes = tree(d3.entries(json)[0]);
23 
24   var link = vis.selectAll("path.link")
25       .data(tree.links(nodes))
26     .enter().append("svg:path")
27       .attr("class", "link")
28       .attr("d", diagonal);
29 
30   var node = vis.selectAll("g.node")
31       .data(nodes)
32     .enter().append("svg:g")
33       .attr("class", "node")
34       .attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; })
35 
36   node.append("svg:circle")
37       .attr("r", 4.5);
38 
39   node.append("svg:text")
40       .attr("dx", function(d) { return d.x < 180 ? 8 : -8; })
41       .attr("dy", ".31em")
42       .attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
43       .attr("transform", function(d) { return d.x < 180 ? null : "rotate(180)"; })
44       .text(function(d) { return d.data.key; });
45 });
Copyright © 2011 Mike Bostock
Fork me on GitHub