liveBook · Manning

D3.forceCollide()

As explained in D3.js in Action, Third Edition

forceCollide is a D3 force function that applies collision constraints to simulation nodes.

d3.forceCollide() is a collision force for a D3 force simulation. It keeps nodes from overlapping by enforcing a minimum distance between their centers. Set that distance with radius(). section 12.4.1

Use a radius larger than a circle’s visible radius to create padding. For circles with radius 10, radius(12) leaves 2 px of space between their edges. Without positioning forces, collision-separated nodes gather into a circle. section 12.4.1

Build a beeswarm

Combine collision with forceX() to align nodes by a value and forceY(0) to draw them toward the vertical center. The collision force preserves each point while preventing overlap. section 12.4.1

Match collision spacing to node size

When nodes have varying radii, store each node’s radius and return d.radius + 2 from radius() to retain a 2 px gap. section 12.4.1

Figure 12.14 The collision force d3.forceCollide() prevents the nodes from overlapping. By setting its radius() accessor function, we impose a minimum distance between the center of each node. Without positioning forces, the nodes naturally aggregate into a circle. If we combine the collision force with a positioning force, we obtain a flattened shape that resembles a beeswarm chart.
figure

Compare the circular cluster produced by collision alone with the flattened beeswarm shape produced when a positioning force is added. section 12.4.1

How D3.js in Action, Third Edition covers it

How deep it goes
Explains radius-based spacing and combines the force with x and y positioning through simulation code.
Examples
Demonstrates 300 normally distributed nodes and variable-size Romeo and Juliet character circles.
What it assumes
Assumes a D3 force simulation and SVG nodes, then teaches collision spacing from its radius accessor.
What you can do after
Apply it via D3 forceSimulation() to separate fixed- or variable-radius circles with optional padding.
How it connects
Connects force simulations with forceX(), forceY(), beeswarm charts, point scales, and normal distributions.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.