Force directed graph: charge forces

There’s two types of forces in the d3-force module. These are preshipped forces and custom forces.

Preshipped forces have already been written for you. Custom forces you write yourself.

Here we cover a preshipped force - forceManyBody(). This is perhaps the defining force of the force-directed graph.

You use this force to simulate the charged-particles model, where every node repels (or attracts) every other node until we reach a stable state. It’s fascinating.

Parameters Link to heading

There’s four parameters that you can play with here.

Out of these I found that there’s two particularly useful ones - strength and distanceMax. The other two are theta and distanceMin.

strength: analogous to the charge in version 3 of d3 and specifies how repulsive or attractive each node is to each other. Negative numbers indicate a repulsive force and positive numbers an attractive force.

Strength defaults to -30 upon installation. I imagine that you’ll usually want to keep this negative to produce traditional force directed graphs.

Note that there’s a balance between size of node and strength of repulsive force. If you make your nodes large, you’ll likely want to increase the charge so that they’re further apart.

distanceMax: used to specify the maximum distance on which the charge force applies.

This is most useful when you have many nodes on the screen. Then the simulation has to update all your nodes and links, paint them to the screen, and then do it all again for every tick.

You can imagine how lag is introduced into the graph.

Improving matters could be as simple as providing a small value in the distance_max parameter so that the force calculations will take less time for each node.

Better performance all round.

theta: used as a parameter in the Barnes-Hut approximation that d3 uses to compute the force layout.

You can get some pretty trippy results by playing around with this, but I haven’t figured out the best way to use it yet.

distanceMin: used to avoid instability in the graph by nodes being too close to each other.

I imagine this would be most helpful if you had an attractive force between nodes since they would naturally gravitate to the same point.


Hope you found that useful! Click here to view to the rest of the force directed graph series.