Does d3.js force layout allow dynamic linkDistance?

riccardo.tasso picture riccardo.tasso · May 15, 2013 · Viewed 9.7k times · Source

I'm using the force layout to represent a directed unweighted network. My inspiration comes from the following example: http://bl.ocks.org/mbostock/1153292

enter image description here

My problem is that in my case there much more links between nodes and I have the feeling that giving a fixed linkDistance, which is always the same, is a very big constraint for my layout.

Is it possible to set a dynamic linkDistance, such that a link grows in length if it's useful to reduce link crossing inside the graph?

Answer

Lars Kotthoff picture Lars Kotthoff · May 15, 2013

From the documentation:

force.linkDistance([distance])

If distance is specified, sets the target distance between linked nodes to the specified value. If distance is not specified, returns the layout's current link distance, which defaults to 20. If distance is a constant, then all links are the same distance. Otherwise, if distance is a function, then the function is evaluated for each link (in order), being passed the link and its index, with the this context as the force layout; the function's return value is then used to set each link's distance. The function is evaluated whenever the layout starts. Typically, the distance is specified in pixels; however, the units are arbitrary relative to the layout's size.

Note that the link distance is still adjusted as the layout runs. You may also find setting linkStrength() useful.