bananasplit bananasplit - 1 year ago 115
Javascript Question

D3.js fixed width tree with limited indentation

From the d3.js example

I would like to use tree.size to specify the width of the tree, but I find the default indentation of the children too large. As mentioned in the doc, [if I use tree.nodeSize it will cancel the effect of tree.size][1]: "The nodeSize property is exclusive with tree.size; setting tree.nodeSize sets tree.size to null."

var tree = d3.layout.tree()
//.nodeSize([1, 20]);
.size([10, 300]);

I created a custom jsfiddle for clarity:

You can see that the first child is way on the right. I'd like it to be approx 20 px from the left side max, but I don't want the tree to be able to grow past its width either when I deploy the 'analytics' node.

Any way to get the best of both worlds?

UPDATE: here is a working example:

Answer Source

Assuming I understand your question correctly, you can accomplish this by "normalizing depth" for each of your nodes.

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

just add this near your comment // Compute the "layout" and play with the value 100 to get it the way you want.

edit: you could also set your tree size with a var width and then change { d.y = d.depth * 100; } to { d.y = d.depth * width/someNumber; } to make it dependant on the overall tree size

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download