One way to do it is to discover the depth of the tree and set the depth
property of each node that doesn't have any children to that value.
Assuming your tree data is as follows:
var data = [
{
"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A",
"parent": "Top Level",
"children": [ ...
And you created a tree using:
var tree = d3.layout.tree();
You can get the depth
of the tree by searching each node for the max value of depth
:
var treeDepth = d3.max(tree(data[0]), function(d) { return d.depth; });
Once you have that, you can reset it every time you recompute the tree layout:
tree.nodes(data[0]).forEach(function(d) {
var depthSize = 50;
if (!d.children) { // this node has no children
d.depth = treeDepth; // set depth to depth of tree
}
d.y = d.depth * depthSize; // recalculate y
});
This works for trees laid out as in your example (from left to right). For top-down layouts you have to change dx
instead.
Here is a JSFiddle with a working solution adapted from this example .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.