Skip to content

Instantly share code, notes, and snippets.

@Rnhatch
Last active April 12, 2017 01:00
Show Gist options
  • Save Rnhatch/1563298 to your computer and use it in GitHub Desktop.
Save Rnhatch/1563298 to your computer and use it in GitHub Desktop.
Force Directed Layout
<!DOCTYPE html>
<html>
<head>
<title>Force-Directed Layout</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.7.4/d3.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.7.4/d3.geom.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.7.4/d3.jslayout.js"></script>
// https://cdnjs.cloudflare.com/ajax/libs/d3/4.7.4/d3.js //
</head>
<body>
<script type="text/javascript">
var w = 1100,
h = 800,
fill = d3.scale.category10(),
nodes = [],
foci = [{ x: 650, y: 400}],
c = d3.scale.linear().domain([0, 1]).range(["hsl(200, 50%, 50%)", "hsl(330, 100%, 50%)"]).interpolate(d3.interpolateHsl),
r = d3.scale.linear().domain([0,1]).range([20,40]);
// foci = [{ x: 150, y: 150 }, { x: 350, y: 250 }, { x: 700, y: 400}];
var vis = d3.select("body").append("svg:svg")
.attr("width", w)
.attr("height", h);
var force = d3.layout.force()
.nodes(nodes)
.links([])
.linkDistance(90)
// .charge(function(d, i) { return i ? 0 : -2000; })
.gravity(0)
.size([w, h]);
force.on("tick", function(e) {
// Push nodes toward their designated focus.
var k = .01 * e.alpha;
nodes.forEach(function(o, i) {
o.y += (foci[o.id].y - o.y) * k;
o.x += (foci[o.id].x - o.x) * k;
});
vis.selectAll("circle.node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
// for (i = 0; i < 100; i++) {
setInterval(function() {
nodes.push({ id: ~ ~(Math.random() * foci.length) });
force.start();
vis.selectAll("circle.node")
.data(nodes)
.enter().append("svg:circle")
.attr("class", "node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
// .attr("r", 20)
.attr("r", function() { return r(Math.random()) })
.attr("fill", function() { return c(Math.random()) })
.attr("fill-opacity", .5)
.style("stroke", function(d) { return d3.rgb(fill(d.id)).darker(2); })
.style("stroke-width", 1.5)
.call(force.drag);
}, 500);
// };
</script>
</body>
</html>
@Rnhatch
Copy link
Author

Rnhatch commented Jan 13, 2012

See this in action at http://bl.ocks.org/1563298

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment