Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Graph orientation and node positioning in d3.js

Thanks to this earlier question, I produced a static fixed-layout graph as below using force layout in d3.js:

enter image description here

and I have two specific questions to further customize the layout:

First, I notice that initializing nodes positions deterministically (e.g. done diagonally here, see the script for details) fixes the positions of the nodes, and the orientation of the nodes seem to depend on this initialization as well as the dimensions of the force graph*. I wonder how can I make the nodes A, D, E, F, I in the graph above aligned horizontally? In other words, I want to turn the orientation of the graph anti-clockwise for roughly 45 degrees. I have 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 produced output has all the nodes and edges horizontally at where they were initialized.

Second, is it true that the force graph is automatically centered within the svg element? If no, how can we make it so? If yes, how can we specify a center for the force graph within the svg element?

(* Note: strangely, when setting .size([w, h]) where w = h for the force graph, and deterministically initializing the nodes along a diagonal, all the nodes and edges are positioned along that diagonal in the output, why?)

like image 999
MLister Avatar asked Aug 10 '12 20:08

MLister


1 Answers

Try adding a custom gravity force applied on each tick which pulls the nodes towards the horizontal line. Something like this:

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 there is a small gravity force by default which pulls the nodes towards the center.

like image 122
Ilya Boyandin Avatar answered Oct 21 '22 00:10

Ilya Boyandin