Skip to content

Instantly share code, notes, and snippets.

@mbostock
Forked from mbostock/.block
Last active Feb 9, 2016
Embed
What would you like to do?
Force Layout Multiples (Independent)
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500,
padding = 1.5, // separation between nodes
maxRadius = 12;
var n = 200, // total number of nodes
m = 10; // number of distinct clusters
var color = d3.scale.category10()
.domain(d3.range(m));
var x = d3.scale.ordinal()
.domain(d3.range(m))
.rangeBands([0, width]);
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)
};
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.nest()
.key(function(d) { return d.color; })
.entries(nodes)
.forEach(force);
function force(entry, i) {
var nodes = entry.values;
var force = d3.layout.force()
.nodes(nodes)
.size([x.rangeBand(), height])
.gravity(.2)
.charge(0)
.on("tick", tick)
.start();
var circle = svg.append("g")
.attr("transform", "translate(" + x(i) + ")")
.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 tick(e) {
circle
.each(collide(.5))
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
// Resolves collisions between d and all other circles.
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 + 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