Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 44 ยท Layouts and Hierarchies

Force Simulations

Learn how d3.forceSimulation works: many-body, center, collide, x/y and link forces, alpha cooling, tick events and how to draw simulated nodes.

A force simulation is a small physics engine. You give it a list of nodes (objects), add forces that push and pull them, and the simulation updates each node's position over many small steps called ticks. After a few hundred ticks the nodes settle into a stable arrangement. This is how force-directed graphs, bubble clusters and "beeswarm" plots are made.

The simulation lives in the d3-force module (included in the full D3 bundle). Like layouts, it does not draw anything: it writes x and y onto your node objects, and you copy those numbers into the DOM.

Your first simulation

JavaScript
const nodes = d3.range(40).map(i => ({ id: i }));

const sim = d3.forceSimulation(nodes)
  .force("charge", d3.forceManyBody().strength(-30))
  .force("center", d3.forceCenter(250, 150))
  .on("tick", ticked);

D3 adds x, y, vx and vy (position and velocity) to every node. The tick event fires after each step, so ticked is the place to update the SVG.

Nodes repel and center

Watch the circles spread out from the middle and stop. If you press Run again, the starting positions are always the same: D3 places new nodes on a deterministic spiral, so results are reproducible.

The built-in forces

Each force has a name you choose when you add it with .force(name, force). Adding a force under an existing name replaces it, and .force(name, null) removes it.

Force What it does
forceManyBody() Every node attracts (positive strength) or repels (negative) all others. The classic "charge".
forceCenter(x, y) Shifts all nodes so their average position is the point. Does not pull individually.
forceX(x) / forceY(y) Pulls each node toward a coordinate. Strength and target can depend on the node.
forceRadial(r, cx, cy) Pulls nodes toward a circle of radius r.
forceCollide(r) Stops circles overlapping; r can be a function of the node.
forceLink(links) Treats pairs of nodes as springs of a given distance. See Force-directed graphs.

Forces are combined: each tick every force adjusts the velocities, then velocities are applied to positions.

Alpha: how the simulation cools down

The simulation has a "temperature" called alpha, starting at 1. Every tick multiplies it toward alphaTarget (0 by default), so forces get weaker and movement stops. Relevant settings:

  • alphaDecay (default about 0.0228) is how fast it cools. Smaller values mean longer simulations. The default needs roughly 300 ticks.
  • alphaMin (default 0.001) is the level at which the simulation stops and fires end.
  • velocityDecay (default 0.4) is the friction: higher values slow nodes down faster.
  • sim.alphaTarget(0.3).restart() heats it up again, which you do while dragging. Set alphaTarget(0) on drag end to let it cool.

sim.stop() pauses the timer, and sim.restart() resumes. If you want no animation at all, stop the simulation and call sim.tick(300) once to run 300 steps synchronously, then draw the final positions. This is much faster and perfect for static charts:

JavaScript
const sim = d3.forceSimulation(nodes).force(...).stop();
sim.tick(300);
// draw using node.x and node.y

A bubble cluster with collide and x/y forces

forceCollide turns a simulation into a packing algorithm. Combine it with weak forceX and forceY forces that pull nodes toward a target, and nodes form groups without overlapping:

Grouped bubbles

Here the simulation never animates: we stopped it, ran 250 ticks synchronously and drew once. That is the right approach when the layout is only needed once.

flowchart LR
  A["Nodes + forces"] --> B["tick: forces change vx, vy"]
  B --> C["positions += velocities"]
  C --> D["alpha cools"]
  D -->|"alpha > alphaMin"| B
  D -->|"alpha <= alphaMin"| E["end event"]

The simulation loops until it has cooled.

Configuring forces with functions

Most force settings accept either a number or a function of the node, so you can vary the behaviour per node. For example forceManyBody().strength(d => -d.r * 3) makes large nodes repel harder, and forceCollide().radius(d => d.r + 2).iterations(3) increases collision accuracy at the cost of speed. Use .distanceMax(200) on many-body to ignore far-away nodes, which speeds things up for big graphs.

Fixing and moving nodes

Setting node.fx and node.fy pins a node at a position: the simulation will not move it. Set them back to null to release it. This is how dragging works: while the pointer is down you write the pointer position into fx and fy.

Common mistakes

  • Replacing the node objects. The simulation mutates the objects you pass in; if you create new objects each render, positions are lost.
  • Reading x and y before any tick has run: they are undefined until the first tick (or the node's initial position).
  • Updating the DOM with a fresh data join on every tick. Join once, then only update attributes in tick.
  • Forgetting .stop() when you intend to call .tick(n) manually: the timer would keep running at the same time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a negative strength on forceManyBody do?

    Positive strength attracts nodes to one another and negative strength repels them. Repulsion is the usual setting for graphs.
  2. 2. How do you compute the final layout without any animation?

    Stop the timer, run a number of ticks synchronously, then read the positions once.
  3. 3. What do fx and fy do on a node?

    When fx and fy are set the simulation keeps x and y equal to them. Setting them to null releases the node.
  4. 4. Which force stops circles from overlapping?

    forceCollide treats each node as a circle with a radius and pushes overlapping nodes apart.

Summary

  • d3.forceSimulation(nodes) adds x, y, vx, vy to your nodes and updates them each tick.
  • Combine forces: many-body, center, x/y, radial, collide and link.
  • alpha cools toward zero; heat it up with alphaTarget(...).restart().
  • For static results, stop() the simulation and call tick(n) once.
  • Pin nodes with fx and fy.

Next: Force-Directed Graphs