Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase distance between child nodes in a D3 Collapsible Tree?

I have tried the suggestion in this answer but it makes no difference whatsoever.

I'm using the standard collapsible tree example from the D3 website.

Specifically, I've added the following, as the answer suggests:

var tree = d3.layout.tree()
    .separation(function(a, b) { return ((a.parent == root) && (b.parent == root)) ? 3 : 1; })
    .size([height, width - 160]);

But nothing. The documentation also suggests adjusting the separation attribute but modifying the default one listed there with any random value seems to produce no effect on the layout:

.separation(function(a, b) { return a.parent == b.parent ? 1 : 7; }) // no effect

Am I missing something obvious? I've not done any JavaScript or jQuery and it's my first time using this library so I'm just trying to go along as I can.

The reason for trying to accomplish this is that the names of each node are quite long and when expanding a child node with lots of children, they overlap in an ugly way (I'm using different json data to the one in the example).

like image 236
Nobilis Avatar asked Jul 18 '14 08:07

Nobilis


3 Answers

A helpful and generous friend of mine, working in the web development industry, has been able to crack the problem for me and the solution is as follows.

The line that takes care of the distance is this:

nodes.forEach(function(d) { d.y = d.depth * 180; });

This specifies a separation in pixels (in this case 180) between a parent and a child.

If the text also needs to be adjusted, the line in question is:

.attr("x", function(d) { return d.children || d._children ? -10 : 10; })

This is spacing out the text only and it's either on the left or the right of the node depending on whether or not it's a child node. Adjusting by -10 or 10 should produce visible results.

Hope it is of help to anyone who comes across this problem!

like image 125
Nobilis Avatar answered Nov 09 '22 01:11

Nobilis


nodes.forEach(function(d) { d.y = d.depth * 180; });

It works for me. Here 180 is the distance in pixel between two nodes. You can change the value on your demand.

like image 38
Olioul Islam Rahi Avatar answered Nov 09 '22 01:11

Olioul Islam Rahi


var tree = d3.layout.tree().nodeSize([150, 40]);

Here you change the width value, to change the distance between adjacent child nodes.

like image 38
Deepika T S Avatar answered Nov 09 '22 02:11

Deepika T S