Skip to content

Instantly share code, notes, and snippets.

Last active April 7, 2023 09:29
Show Gist options
  • Save mbostock/1667139 to your computer and use it in GitHub Desktop.
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=""></script>
var svg ="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())
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() {
// See
for (var i = 0, n = Math.ceil(Math.log(simulation.alphaMin()) / Math.log(1 - simulation.alphaDecay())); i < n; ++i) {
.attr("stroke", "#000")
.attr("stroke-width", 1.5)
.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return; })
.attr("y2", function(d) { return; });
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 4.5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment