Created
September 17, 2012 01:14
-
-
Save billroy/3735080 to your computer and use it in GitHub Desktop.
Force directed layout with titles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Force-Directed Layout</title> | |
<script type="text/javascript" src="../../d3.v2.js"></script> | |
<style type="text/css"> | |
circle { | |
stroke-width: 1.5px; | |
} | |
line { | |
stroke: #999; | |
} | |
</style> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
var width = 960, | |
height = 500, | |
radius = 6, | |
fill = d3.scale.category20(); | |
var force = d3.layout.force() | |
.gravity(.01) | |
.charge(-120) | |
.linkDistance(30) | |
.size([width, height]); | |
var svg = d3.select("body").append("svg") | |
.attr("width", width) | |
.attr("height", height); | |
d3.json("miserables.json", function(json) { | |
var link = svg.selectAll("line") | |
.data(json.links) | |
.enter().append("line"); | |
var node_title = svg.selectAll("text") | |
.data(json.nodes) | |
.enter().append("text") | |
.attr("text-anchor", "start") | |
.attr("dy", "1em") | |
.text(function(d) { return d.name; }); | |
var node = svg.selectAll("circle") | |
.data(json.nodes) | |
.enter().append("circle") | |
.attr("r", radius - .75) | |
.style("fill", function(d) { return fill(d.group); }) | |
.style("stroke", function(d) { return d3.rgb(fill(d.group)).darker(); }) | |
.call(force.drag); | |
force | |
.nodes(json.nodes) | |
.links(json.links) | |
.on("tick", tick) | |
.start(); | |
function tick() { | |
node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); }) | |
.attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, d.y)); }); | |
node_title.attr("x", function(d) { return d.x; }) | |
.attr("y", function(d) { return d.y; }); | |
link.attr("x1", function(d) { return d.source.x; }) | |
.attr("y1", function(d) { return d.source.y; }) | |
.attr("x2", function(d) { return d.target.x; }) | |
.attr("y2", function(d) { return d.target.y; }); | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment