Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active April 7, 2023 09:29
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mbostock/1667139 to your computer and use it in GitHub Desktop.
Static Force Layout
license: gpl-3.0

This demonstrates how to produce a static force-directed graph layout with d3-force. Rather than updating the graph with each tick, we run the graph a fixed number of times, and then display it once. To avoid freezing the user interface, it may be desirable to compute the force-directed layout in a web worker.

<!DOCTYPE html>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var n = 100,
nodes = d3.range(n).map(function(i) { return {index: i}; }),
links = d3.range(n).map(function(i) { return {source: i, target: (i + 3) % n}; });
var simulation = d3.forceSimulation(nodes)
.force("charge", d3.forceManyBody().strength(-80))
.force("link", d3.forceLink(links).distance(20).strength(1).iterations(10))
.force("x", d3.forceX())
.force("y", d3.forceY())
.stop();
var loading = svg.append("text")
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.text("Simulating. One moment please…");
// Use a timeout to allow the rest of the page to load first.
d3.timeout(function() {
loading.remove();
// See https://github.com/d3/d3-force/blob/master/README.md#simulation_tick
for (var i = 0, n = Math.ceil(Math.log(simulation.alphaMin()) / Math.log(1 - simulation.alphaDecay())); i < n; ++i) {
simulation.tick();
}
g.append("g")
.attr("stroke", "#000")
.attr("stroke-width", 1.5)
.selectAll("line")
.data(links)
.enter().append("line")
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
g.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(nodes)
.enter().append("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 4.5);
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment