Skip to content

Instantly share code, notes, and snippets.

@njvack
Created October 26, 2011 16:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save njvack/1316832 to your computer and use it in GitHub Desktop.
Save njvack/1316832 to your computer and use it in GitHub Desktop.
Beeswarm plot with gravity and collisions
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Beeswarm plot - collision detection</title>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.geom.js"></script>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.layout.js"></script>
</head>
<body>
<div id="body">
<div id="chart"></div>
</div>
<script type="text/javascript">
function norm() {
var res, i;
res = 0;
for (i = 0; i < 10; i += 1) {
res += Math.random()*2-1
}
return res;
}
var w = 500,
h = 500;
var nodes = d3.range(400).map(function() {
var true_y = (norm()*50)+250;
return {
radius: 4,
y: true_y,
true_x: 250,
true_y: true_y }
});
var force = d3.layout.force()
.gravity(0)
.charge(0)
.friction(0.9)
.nodes(nodes)
.size([w, h]);
var root = nodes[0];
root.radius = 0;
root.fixed = true;
force.start();
var svg = d3.select("#chart").append("svg:svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("circle")
.data(nodes)
.enter().append("svg:circle")
.attr("r", function(d) { return d.radius; })
.style("fill", 'steelblue')
.style("stroke", "black");
force.on("tick", function(e) {
var q,
node,
i = 0,
n = nodes.length;
var q = d3.geom.quadtree(nodes);
while (++i < n) {
node = nodes[i];
q.visit(collide(node));
xerr = node.x - node.true_x;
yerr = node.y - node.true_y;
node.x -= xerr*0.005;
node.y -= yerr*0.8;
}
svg.selectAll("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
function collide(node) {
var r = node.radius,
nx1,
nx2,
ny1,
ny2,
xerr,
yerr;
nx1 = node.x - r;
nx2 = node.x + r;
ny1 = node.y - r;
ny2 = node.y + r;
return function(quad, x1, y1, x2, y2) {
if (quad.point && (quad.point !== node)) {
var x = node.x - quad.point.x,
y = node.y - quad.point.y,
l = Math.sqrt(x * x + y * y),
r = node.radius + quad.point.radius;
if (l < r) {
// we're colliding.
var xnudge, ynudge, nudge_factor;
nudge_factor = (l - r) / l * .4;
xnudge = x*nudge_factor;
ynudge = y*nudge_factor;
node.x -= xnudge;
node.y -= ynudge;
quad.point.x += xnudge;
quad.point.y += ynudge;
}
}
return x1 > nx2
|| x2 < nx1
|| y1 > ny2
|| y2 < ny1;
};
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment