Graph orientation and node location in d3.js

Thanks to this earlier question , I created a static fixed layout graph, as shown below, using the force diagram in d3.js:

enter image description here

and I have two specific questions for further layout setup:

Firstly, I notice that the initialization of nodes is deterministically positioned (for example, diagonally here, see the script ) fixes the positions of nodes and the orientation of nodes, it seems, depend on this initialization, as well as on the size of the force graph *. I wonder how I can make the nodes A, D, E, F, Iin the graph above align horizontally ? In other words, I want to rotate the graph orientation counterclockwise by about 45 degrees. I tried to initialize the nodes horizontally in the middle:

nodes.forEach(function(d, i) { d.x = w / size * i; d.y = h / 2; });

but the result has all the nodes and edges horizontally where they were initialized.

Secondly, is it true that the force graph is automatically centered inside the element svg? If not, how can we do this? If so, how can we indicate the center for the graph of the force inside the element svg?

(* Note: strangely enough, when setting .size([w, h])where w = hfor the force graph and the deterministic initialization of nodes diagonally, all nodes and edges are located along this diagonal at the output, why?)

+5
source share
1 answer

Try adding a custom gravity applied to each tick that pulls nodes to a horizontal line. Something like that:

force.on('tick', function(e) {
  nodes.forEach(function(d) {
    d.y += (height/2 - d.y) * e.alpha;
  });
})

To your second question, I believe it is not centered, but by default there is a small force of gravity that pulls the nodes towards the center.

+2

All Articles