Force-Directed Graph

Layout algorithm inspired by Tim Dwyer and Thomas Jakobsen. Data based on character coappearence in Victor Hugo’s Les Misérables, compiled by Donald Knuth.

Source Code

 1 var w = 960,
 2     h = 500,
 3     fill = d3.scale.category20();
 4 
 5 var vis = d3.select("#chart")
 6   .append("svg:svg")
 7     .attr("width", w)
 8     .attr("height", h);
 9 
10 d3.json("miserables.json", function(json) {
11   var force = d3.layout.force()
12       .charge(-60)
13       .nodes(json.nodes)
14       .links(json.links)
15       .size([w, h])
16       .start();
17 
18   var link = vis.selectAll("line.link")
19       .data(json.links)
20     .enter().append("svg:line")
21       .attr("class", "link")
22       .style("stroke-width", function(d) { return Math.sqrt(d.value); })
23       .attr("x1", function(d) { return d.source.x; })
24       .attr("y1", function(d) { return d.source.y; })
25       .attr("x2", function(d) { return d.target.x; })
26       .attr("y2", function(d) { return d.target.y; });
27 
28   var node = vis.selectAll("circle.node")
29       .data(json.nodes)
30     .enter().append("svg:circle")
31       .attr("class", "node")
32       .attr("cx", function(d) { return d.x; })
33       .attr("cy", function(d) { return d.y; })
34       .attr("r", 5)
35       .style("fill", function(d) { return fill(d.group); })
36       .call(force.drag);
37 
38   node.append("svg:title")
39       .text(function(d) { return d.name; });
40 
41   vis.style("opacity", 1e-6)
42     .transition()
43       .duration(1000)
44       .style("opacity", 1);
45 
46   force.on("tick", function() {
47     link.attr("x1", function(d) { return d.source.x; })
48         .attr("y1", function(d) { return d.source.y; })
49         .attr("x2", function(d) { return d.target.x; })
50         .attr("y2", function(d) { return d.target.y; });
51 
52     node.attr("cx", function(d) { return d.x; })
53         .attr("cy", function(d) { return d.y; });
54   });
55 });
Copyright © 2011 Mike Bostock
Fork me on GitHub