How to Visualize a Graph
You need two things to make a graph sort itself a visual appealing way.
- A spring force between every two nodes connected by an edge. I use a spring that wants to maintain a distance of one and has a strength of one.
- A repellent force between every two nodes. I use a spring that has a strength of 0.02 and wants to maintain a distance of 50.
The Algorithm:
Note: My version of this code is about 30 lines, and it could be smaller.
- Copy all of the existing X and Y values for each node into the array Xnew and Ynew
- For each node I
- For each node J
- if (i == j) skip this iteration
- If (I is in the same place as J)
- Move change newX and newY a bit
- else
- compute a springX and springY for length 50 with strength 0.02
- If there is an edge, add a springX and springY for length 1 with strength 1.0
- Update newX and newY based on springX and springY
- copy newX and newY into X and Y
How to model a spring:
The force of a spring of length LENGTH is given by CONSTANT * (LENGTH - DISTANCE)
Points:
10 -- Can have the graph evolve nicely
5 -- Only one pair of array copies per itearion.
5 -- No array copies per iteration.
-2 -- Per day after Wed March 24
Double Buffering:
See http://euclid.nmu.edu/~randy/Classes/CS120a/DoubleBuffering/ for a how-to. You probably won't need this.
The source.