Skip to content

Instantly share code, notes, and snippets.

@tcgarvin
Forked from mbostock/.block
Last active July 31, 2018 21:02
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 tcgarvin/05b9faa1df35769c07a2f9aceabfa80b to your computer and use it in GitHub Desktop.
Save tcgarvin/05b9faa1df35769c07a2f9aceabfa80b to your computer and use it in GitHub Desktop.
Multi-Foci Force Layout
license: gpl-3.0

Ported to v5 as a sanity check while I was debugging another visualization

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node {
stroke-width: 1.5px;
}
</style>
<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
var width = 960,
height = 500;
var fill = d3.scaleOrdinal(d3.schemeCategory10);
var nodes = [],
foci = [{x: 150, y: 150}, {x: 350, y: 250}, {x: 700, y: 400}];
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.forceSimulation(nodes)
.force('nbody', d3.forceManyBody())
.force('foci', alpha => {
for (var i = 0, n = nodes.length, o, k = alpha * 0.1; i < n; ++i) {
o = nodes[i];
o.vx += (foci[o.id].x - o.x) * k;
o.vy += (foci[o.id].y - o.y) * k;
}
})
.alphaTarget(0.25)
.on("tick", tick);
var node = svg.selectAll("circle");
function tick(e) {
node
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
}
function add() {
nodes.push({
id: ~~(Math.random() * foci.length),
x: Math.random() * width,
y: Math.random() * height
});
force.nodes(nodes);
node = svg.selectAll("circle").data(nodes);
node = node.enter().append("circle")
.attr("class", "node")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 8)
.style("fill", function(d) { return fill(d.id); })
.style("stroke", function(d) { return d3.rgb(fill(d.id)).darker(2); })
.merge(node);
}
setInterval(add, 500);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment