Skip to content

Instantly share code, notes, and snippets.

@mathieue
Created September 24, 2014 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathieue/30bc5019572b176f140a to your computer and use it in GitHub Desktop.
Save mathieue/30bc5019572b176f140a to your computer and use it in GitHub Desktop.
d3.js force layout experiments
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node {
fill: #000;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500,
padding = 2, // separation between nodes
maxRadius = 3;
var n = 200, // total number of nodes
m = 4; // number of distinct clusters
var color = d3.scale.category10()
.domain(d3.range(m));
var x = d3.scale.ordinal()
.domain(d3.range(m))
.rangePoints([0, width], 1);
var nodes = d3.range(n).map(function() {
var i = Math.floor(Math.random() * m),
v = (i + 1) / m * -Math.log(Math.random());
return {
radius: Math.sqrt(v) * maxRadius,
color: color(i),
cx: x(i),
cy: height / 2
};
});
var force = d3.layout.force()
.nodes(nodes)
.size([width, height])
.gravity(0)
.charge(-3)
.friction(0.9)
.on("tick", tick)
.start();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var circle = svg.selectAll("circle")
.data(nodes)
.enter().append("circle")
.attr("r", function(d) { return d.radius; })
.style("fill", function(d) { return d.color; })
.call(force.drag);
function makenode() {
var i = Math.floor(Math.random() * m),
v = (i + 1) / m * -Math.log(Math.random());
var node = {
radius: Math.sqrt(v) * maxRadius,
color: color(i),
cx: x(i),
cy: height / 2
};
nodes.push(node);
circle = circle.data(nodes);
circle.enter().append("circle")
.attr("r", function(d) { return d.radius; })
.style("fill", function(d) { return d.color; })
.call(force.drag);
force.start();
}
setInterval(function(){return makenode(); }, 100)
function tick(e) {
circle
.each(gravity(.1 * e.alpha))
.each(collide(0.01))
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
// Move nodes toward cluster focus.
function gravity(alpha) {
return function(d) {
d.y += (d.cy - d.y) * alpha;
d.x += (d.cx - d.x) * alpha;
};
}
// Resolve collisions between nodes.
function collide(alpha) {
var quadtree = d3.geom.quadtree(nodes);
return function(d) {
var r = d.radius + maxRadius + padding,
nx1 = d.x - r,
nx2 = d.x + r,
ny1 = d.y - r,
ny2 = d.y + r;
quadtree.visit(function(quad, x1, y1, x2, y2) {
if (quad.point && (quad.point !== d)) {
var x = d.x - quad.point.x,
y = d.y - quad.point.y,
l = Math.sqrt(x * x + y * y),
r = d.radius + quad.point.radius + (d.color !== quad.point.color) * padding;
if (l < r) {
l = (l - r) / l * alpha;
d.x -= x *= l;
d.y -= y *= l;
quad.point.x += x;
quad.point.y += y;
}
}
return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
});
};
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment