Skip to content

Instantly share code, notes, and snippets.

@ericsoco
Last active October 18, 2016 04:13
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 ericsoco/c3fdb4c844a88101f606e9db08e66845 to your computer and use it in GitHub Desktop.
Save ericsoco/c3fdb4c844a88101f606e9db08e66845 to your computer and use it in GitHub Desktop.
cluster force III
license: mit

Built with blockbuilder.org

forked from ericsoco's block: cluster force II

Moving toward a v4 modular version of Mike Bostock's Clustered Force Layout III.

There are two things worth mentioning here:

  1. Uses v4's forceSimulation()
  2. Modularizes the cluster force, offering an API similar to other core d3-force modules like, e.g., the positioning forces.

This version spawns nodes further from the center and then pulls them toward the center via a custom attract force, also written as a module following the d3-force module format/pattern.

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var width = 960,
height = 500,
padding = 1.5, // separation between same-color nodes
clusterPadding = 6, // separation between different-color nodes
maxRadius = 12;
var n = 200, // total number of nodes
m = 10; // number of distinct clusters
var color = d3.scaleSequential(d3.interpolateRainbow)
.domain(d3.range(m));
// The largest node for each cluster.
var clusters = new Array(m);
var nodes = d3.range(n).map(function() {
var i = Math.floor(Math.random() * m),
r = Math.sqrt((i + 1) / m * -Math.log(Math.random())) * maxRadius,
d = {
cluster: i,
radius: r,
x: Math.cos(i / m * 2 * Math.PI) * 200 + width / 2 + Math.random(),
y: Math.sin(i / m * 2 * Math.PI) * 200 + height / 2 + Math.random()
};
if (!clusters[i] || (r > clusters[i].radius)) clusters[i] = d;
return d;
});
var force = d3.forceSimulation()
// keep entire simulation balanced around screen center
.force('center', d3.forceCenter(width/2, height/2))
// pull toward center
.force('attract', attract()
.target([width/2, height/2])
.strength(0.02))
// cluster by section
.force('cluster', cluster()
.strength(0.7))
// apply collision with padding
.force('collide', d3.forceCollide(d => d.radius + padding)
.strength(0))
.on('tick', layoutTick)
.nodes(nodes);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var node = svg.selectAll("circle")
.data(nodes)
.enter().append("circle")
.style("fill", function(d) { return color(d.cluster/10); });
// ramp up collision strength to provide smooth transition
var transitionTime = 3000;
var t = d3.timer(function (elapsed) {
var dt = elapsed / transitionTime;
force.force('collide').strength(Math.pow(dt, 2) * 0.7);
if (dt >= 1.0) t.stop();
});
function layoutTick(e) {
node
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", function(d) { return d.radius; });
}
// Move d to be adjacent to the cluster node.
// from: https://bl.ocks.org/mbostock/7881887
function cluster () {
var nodes,
strength = 0.1;
function force (alpha) {
// scale + curve alpha value
alpha *= strength * alpha;
nodes.forEach(function(d) {
var cluster = clusters[d.cluster];
if (cluster === d) return;
let x = d.x - cluster.x,
y = d.y - cluster.y,
l = Math.sqrt(x * x + y * y),
r = d.radius + cluster.radius;
if (l != r) {
l = (l - r) / l * alpha;
d.x -= x *= l;
d.y -= y *= l;
cluster.x += x;
cluster.y += y;
}
});
}
force.initialize = function (_) {
nodes = _;
}
force.strength = _ => {
strength = _ == null ? strength : _;
return force;
};
return force;
}
function attract (target) {
let nodes,
targets,
strength = 0.1;
function force (alpha) {
let node, target;
for (let i=0; i<nodes.length; i++) {
node = nodes[i];
target = targets[i];
node.vx += (target[0] - node.x) * strength * alpha;
node.vy += (target[1] - node.y) * strength * alpha;
}
}
force.initialize = _ => {
nodes = _;
targets = new Array(nodes.length);
for (let i=0; i<nodes.length; i++) targets[i] = target(nodes[i], i, nodes);
};
force.strength = _ => {
strength = _ == null ? strength : _;
return force;
};
force.target = _ => {
if (_ == null) _ = target;
target = (typeof _ === 'function') ? _ : () => _;
return force;
};
if (!target) force.target([ 0, 0 ]);
return force;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment