0

I have a tree-based layout using d3, based on the collapsable tree layout example here.

As you can see in the demo, the vertical spacing between nodes is constant for each level in the tree, meaning nodes can bunch together while leaving a lot of white space.

Instead, I'd like each level to take up all the vertical space available. For example, a level with 2 child nodes would have nodes spaced at 0% and 100%, while 3 child nodes would be spaced at 0%, 50% and 100%.

Hopefully this is possible!

Graham
  • 6,484
  • 2
  • 35
  • 39

2 Answers2

0

You may find some helpful information in How to get D3.js's tidy tree graph from reducing the lateral distance of siblings as depth increases (this question has significant overlap with that one) and at https://github.com/mbostock/d3/issues/317. The latter provides a nodeSize argument that I suspect will give a better visual display than arbitrarily shoving the nodes as far apart as possible would.

Community
  • 1
  • 1
Colin Young
  • 3,018
  • 1
  • 22
  • 46
  • Thanks for the pointers. I ended up modifying the method to accept `nodeSize` as a function, meaning I can calculate the size dynamically depending on the node's depth and number of siblings. Works perfectly. – Graham May 06 '13 at 08:38
  • 1
    Good to hear. You should consider submitting a pull request to the d3 project to incorporate your enhancement. – Colin Young May 06 '13 at 13:37
0

You can just modify the 'function update(source)', add the follow codes under this function:

// Recompute the new height
var levelWidth = [1];
var childCount = function(level, n) {
  if(n.children && n.children.length > 0) {
    if(levelWidth.length <= level + 1) levelWidth.push(0);
    levelWidth[level+1] += n.children.length;
    n.children.forEach(function(d) {
      childCount(level + 1, d);
    });
  }
};
childCount(0, root);  
var newHeight = d3.max(levelWidth) * 40; 
tree = tree.size([newHeight, width]);

Refer to this like for the detailed question and answer(Superboggly): Dynamically resize the d3 tree layout based on number of childnodes

Community
  • 1
  • 1
ZhangCC
  • 53
  • 1
  • 9