Recently, I need to implement a relational graph in my work. The node layout in the graph needs to use force-oriented layout, so I was interested in the force-oriented algorithm involved, and I went to study it.
Force-directed graph drawings can be used to describe the relationships between nodes of a graph, distributing nodes to reasonable positions on the canvas, such as describing relationships between enterprises, interpersonal relationships in social networks, etc.
Basic principle of algorithm
Let’s first take a look at a rendering:
The distribution of the points in the above figure is calculated by the force guidance algorithm, which is to regard the nodes as the same charge, and there is a repulsive force between them. This repulsive force simulates Coulomb’s law, and the closer the repulsive force, the greater the repulsive force; if there is a connection between two points, it is regarded as an attractive force between the two points. This attractive force simulates Hooke’s law, and the farther away the attractive force is, the greater the attractive force.
In the initial state, we randomly place points, and then these points will move in space due to attractive forces and repulsive forces until a balance is reached, forming a force-oriented layout.
Repulsive force
Consider each node as an electric charge, and there is a repulsive force between the charges, which is the Coulomb force. According to Coulomb’s law, the repulsive force between electrons can be calculated as follows:
F=ker2q1q2e
We can assume that $q_1 and q_2 $are both 1, then the above formula becomes
F=ker21e
Attractive force
Some particles are entangled by some edges that produce a spring-like Hooker attractive force:
Fs=ks(x−x0)
The repulsive and attractive forces continue to act, the particles tend to balance after continuous displacement, and gradually no longer have relative displacement, and the energy is continuously consumed, and finally tends to zero.
Under the action of attractive force and repulsive force, the coordinates are constantly updated, and after multiple iterations, a stable state is reached, and the convergence is over. Parameters and iterations need to be debugged.
Calculation step
If we want to use code to implement the simplified layout of the force guide diagram, we need several steps.
Set point data nodes, link data links.
Random positioning of points.
Render View
Execution algorithm calculates position, renders view (repeated N times)
Code implementation
In fact, understand the above process, you can fully implement a version of the force-oriented algorithm, I just provide a simple version here, each person to achieve the algorithm and the final effect may be completely different