Force Directed layout in 3D
First of all it's worth to mention all force directed algorithms are iterative. We need to perform multiple iterations of an algorithm, before graph starts looking aesthetically pleasing.
With that in mind, the easiest way to make graph look nice is:
// graph is an instance of `ngraph.graph` object.var layout = graph;for var i = 0; i < ITERATIONS_COUNT; ++ilayout;// now we can ask layout where each node/link is best positioned:graph;graph;
getLinkPosition() will be always the same for
the same node. This is true:
layout === layout;
Reason for this is performance. If you are interested in storing positions somewhere else, you can do it and they still will be updated after each force directed layout iteration.
"Pin" node and initial position
Sometimes it's desirable to tell layout algorithm not to move certain nodes.
This can be done with
var nodeToPin = graph;layout; // now layout will not move this node
If you want to check whether node is pinned or not you can use
method. Here is an example how to toggle node pinning, without knowing it's
var node = graph;layout; // toggle it
What if you still want to move your node according to some external factor (e.g.
you have initial positions, or user drags pinned node)? To do this, call
Like many other algorithms in
ngraph family, force layout monitors graph changes
via graph events.
It keeps layout up to date whenever graph changes:
var graph = ; // empty graphvar layout = graph; // layout of empty graphgraph; // create node 1 and 2, and make link between themlayout; // returns position.
If you want to stop monitoring graph events, call
Since this is force directed layout, sometimes it's desirable to adjust physics settings. Please refer to ngraph.physics.simulator to see source code and simulator parameters. You can pass physics settings as a second argument to layout constructor.
var physicsSettings = gravity: -12; // construct physics simulator settings// pass it as second argument to layout:var layout = graph physicsSettings;
You can always get current physics simulator from layout by checking
property. This is read only property.
If you find standard Euler integration producing too much errors and jitter, consider using verlet integration:
var physicsSettings = integrator: 'verlet';// pass it as second argument to layout:var layout = graph physicsSettings;
Kudos to @annxingyuan for the PR.
Space occupied by graph
Finally, it's often desirable to know how much space does our graph occupy. To
quickly get bounding box use
var rect = layout;// rect.x1, rect.y1, rect.z1 - left top back coordinates of bounding box// rect.x2, rect.y2, rect.z2 - right bottom front coordinates of bounding box
With npm do:
npm install ngraph.forcelayout3d