水平d3树:如何从左上角开始而不是从中间y轴开始?

时间:2013-10-03 09:42:19

标签: javascript svg d3.js

我实际上有一些关于这棵树的问题,但我会分别问他们。

我有一棵树(demo/code),这显然是一个股票d3水平树,除了我附加到子节点的一个小工具提示。

问题是,如何让树从容器的左上方展开而不是从y轴的中间向外辐射?换句话说,我想最终得到这个:

START-----Parent 1-----Child 1
                  \
                   `---Child 2

等,其中START位于SVG容器的左上角。注意:子节点因此应向下和向右扩展。

我一直在研究x和y是如何在这里工作的,但我似乎无法弄清楚如何改变它。

2 个答案:

答案 0 :(得分:2)

您可以通过修改

处的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 1Child 2

nodes.forEach(function(d,i) {
                              d.x = d.numberAfterPeriod * 40 + 20;
                              d.y = d.depth * 180;
                            });

答案 1 :(得分:0)

我已经使用Angualr创建了这个,D3js的树根从左上角开始缩进。对将来可能有用。

D3js indented tree root start at top left

请在此处找到github链接。 https://github.com/AnandanSelvaganesan/angular-d3-tree