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()` adds a collision force to a D3 simulation so nodes do not overlap. Set its `radius()` to leave space around each node: for a circle drawn with radius 10 px, the example uses a collision radius of 12 px to add 2 px of padding. section 12.4.1

Make a beeswarm

Create nodes with values, draw them as SVG circles, then run `forceSimulation().force("x", forceX(d => xScale(d.value))).force("y", forceY(0)).force("collide", forceCollide().radius(7)).nodes(sampleNodes).on("tick", updateNetwork)`. The position forces pull circles toward their values and the vertical center; collision keeps the individual points from overlapping. section 12.4.1

For circles of different sizes, use a function such as `forceCollide().radius(d => d.radius + 2)` to give each node its own collision radius and padding. section 12.4.1

How D3.js in Action, Third Edition covers it

How deep it goes
Shows radius settings and working simulation snippets, but does not explain collision-force internals.
Examples
Uses normally distributed points for a beeswarm and differently sized character nodes with added padding.
What you can do after
Apply it via D3 to keep simulated circles apart while positioning them into a beeswarm.
How it connects
Combines with force simulations, `forceX()`, `forceY()`, SVG circles, and beeswarm charts.

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.