您可以通过修改 x 值来实现该效果
nodes.forEach(function(d) { d.x = /*yourValues*/; d.y = d.depth * 180; });
正如您可能已经意识到的那样,您的特定问题的真正关键是为每个节点提供一个与其级别(即兄弟节点)相关的值。由于您提供的示例已经为depth
每个节点提供了一个值,您始终可以遍历节点并计算这些值,最终产生一个数组,如:
node0 has 0 nodes before it in the same depth (depth 0)
node1 has 0 nodes before it in the same depth (depth 1)
node2 has 1 nodes before it in the same depth (depth 1)
更新forEach
您可以通过将上面的代码替换为以下代码来找到兄弟值并达到预期的效果:
nodes.forEach(function(d) { //iterate through the nodes
if(d.parent != null){ //if the node has a parent
for(var i = 0; i < d.parent.children.length; i++){ //check parent children
if(d.parent.children[i].name == d.name){ //find current node
d.downset = i; //index is how far node must be moved down
}
}
d.parentDownset = d.parent.downset; //must also account for parent downset
}
if(d.downset == null){ d.downset = 0; }
if(d.parentDownset == null){ d.parentDownset = 0; }
d.x = (d.downset * 40) + (d.parentDownset * 40) + 20;
d.y = d.depth * 180;
});
此外,通过示例中孩子的命名方式,您可以解析出后面的数字.
取出1
,Child 1.1
否则0
返回Child 1
和Child 2
nodes.forEach(function(d,i) {
d.x = d.numberAfterPeriod * 40 + 20;
d.y = d.depth * 180;
});