bananasplit bananasplit - 4 months ago 20
Javascript Question

D3.js fixed width tree with limited indentation

From the d3.js example http://bl.ocks.org/mbostock/1093025

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: http://jsfiddle.net/orrw9p1k/1/

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:
http://jsfiddle.net/mneom9bf/

Answer

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