I'm playing around with this example of collapsible tree: http://bl.ocks.org/mbostock/4339083
In this example initially only the root and all of its children are visualized. I was wondering how one could visualize set number of levels (for example the root and two additional levels, meaning the root, its children, and children of roots children).
I tried modifying collapse(d)
function, in which I specified to collapse a node based on its depth
property. Like:
function collapse(d) {
if (d.children && d.depth > 3) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
But then none of the nodes get collapsed, because d.depth
property is undefined
. I dug deeper and understood (correct me if I'm wrong) that depth
property only gets assigned to a node after the nodes
variable gets initialized.
var nodes = tree.nodes(root).reverse();
Now I'm completely stuck. Is there any way to achieve this?
I found the solution to my question. It turns out that nodes don't have parent, position (x, y coordinates), and depth attributes before
tree.nodes(root)
is called, which calculates all of the above mentioned attributes. So what I had to do is call that function before I callcollapse
function. After that it is possible to collapse only those nodes, that are of certain depth, which will visualize only certain number of levels.