back · main · about · writing · notes · reading · d3 · now · contact


Force directed graph: positioning forces
12 Mar 2017 · 311 words

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

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

Here we’ll cover the three preshipped positioning forces:

Using positioning forces is easy. There’s not too many parameters to play with and they’re easy to understand!

forceCenter

forceCenter applies a force to all nodes that’ll bring their centre of mass towards a given point.

The default point is at [0,0], which will be the top left corner of the SVG element. Typically this isn’t much use so you’ll want to change it.

The relative positions of all nodes are kept the same when this force is applied. This is unlike the other two positioning forces (forceX and forceY) that distort the relative positions of the nodes.

forceCenter takes two parameters, one for the x and y position of the centering point.

You can play around with these parameters. Perhaps every tick of the simulation moves the graph a bit. Perhaps the graph jumps around every time you click on it. The choice is yours.

forceX and forceY

These two siblings push nodes towards the desired x and y position.

Unlike forceCenter they will distort the relative positions of nodes. You can have fun with this - perhaps by making a squashed force directed graph, or a beeswarm plot.

forceX and forceY take two parameters:

x (or y): the coordinate that the force pulls nodes towards. Default is 0.

strength: a value in [0,1] that indicates how strongly to pull nodes towards the specified point. The higher the value, the stronger the force.

The value of strength doesn’t have to be in [0,1] but outside this range can lead to some strange consequences.


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


back · main · about · writing · notes · reading · d3 · now · contact