r/d3js • u/KbAccident • 4d ago
Deterministic label placement — ordered sides instead of a force simulation
The usual way to stop D3 labels colliding is a force simulation —
give each label a node, let it settle. It works, but you get a
slightly different arrangement each run, which makes snapshot tests
and reproducible exports awkward.
I tried the other approach: each label gets its anchor and an ordered
list of sides to try — right, top, left, bottom, then the corners.
First side that does not collide with anything already placed wins.
If nothing is free the label is hidden and reported, so you know what
you lost rather than finding it later.
No simulation, no seed. Same input, same output.
Trade-off worth stating: placement is resolved in the order you give
the elements, not optimised globally, so a different order can give a
better arrangement. For labels on a scatter plot that has been fine;
for dense maps I have not tried it.
It is a standalone 200-line file, not a D3 plugin, so you would place
your points with D3 and hand the label elements over. Curious whether
that split is useful or just annoying — and whether anyone here has
settled on something better than force for this.
Demo link in the comments.