我实际上有几个关于这棵树的问题,但我会分开问。
我有一棵树 ( demo/code ),除了我附加到子节点的一点工具提示外,它显然大部分是普通的 d3 水平树。
问题是,如何让树从容器的左上角展开,而不是从 y 轴的中间向外辐射?换句话说,我想以这样的方式结束:
START-----Parent 1-----Child 1
\
`---Child 2
等,其中 START 位于 SVG 容器的左上角。注意:子节点应该因此向下和向右扩展。
我一直在研究 x 和 y 在这里是如何工作的,但我似乎无法弄清楚如何改变它。
最佳答案
您可以通过修改 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)
UPDATE 您可以找到兄弟值并通过将上面的 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;
});
此外,在您的示例中, child 的命名方式,您可以只解析出 之后的数字。
从Child 1.1
中取出1
,否则为Child 1
和Child返回
0
2
nodes.forEach(function(d,i) {
d.x = d.numberAfterPeriod * 40 + 20;
d.y = d.depth * 180;
});
关于javascript - 水平 d3 树 : how to have root starting at top left instead of middle y-axis?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19155832/