algorithmgraphp5.jsforce-layout

Is there a simple(-ish) algorithm for drawing force-directed graphs?


enter image description here

I'm trying to write a little graph visualizer in P5js but I can't find a simple(-ish) algorithm to follow.

I've found ways to do it with D3 and I've found some dense textbook snippets (like this) but I'm looking for something in between the two.

Can someone explain the simplest algorithm for drawing a graph (force-directed or otherwise) or point me to a good resource?

Thanks for your help!


Solution

  • I literally just started something similar.

    It's fairly easy to code, you just need to think about the 3 separate forces acting on each node, add them together and divide that by the mass of the node to get the movement of each node.

    1. Gravity, put a simple force acting towards the centre of the canvas so the nodes dont launch themselves out of frame

    2. Node-Node replusion, You can either use coulombs force (which describes particle-particle repulsion) or use the gravitational attraction equation and just reverse it

    3. Connection Forces, this ones a little tricky, define a connection as 2 nodes and the distance between them. when the actual distance between them is different from the defined distance, add a force in the direction of the connection multiplied by the difference between the defined and the actual distance