javascript - 水平 d3 树 : how to have root starting at top left instead of middle y-axis?

标签 javascript svg d3.js

我实际上有几个关于这棵树的问题,但我会分开问。

我有一棵树 ( 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 1Child返回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/

相关文章:

javascript - 如何防止.htaccess跨域javascript加载?

javascript - D3 动态 json 键名

javascript - 引入 d3.js 的麻烦

javascript - 如何在javascript中使用shift + click?

javascript - querySelectorAll 和 getElementsBy* 方法返回什么?

javascript - 如何在单击按钮后添加新行,html jquery

javascript - 使用#hash 从地址栏刷新页面

html - HTML 中的内联 SVG - 相同的字体大小呈现更大

java - 从 XML 中提取 SVG。选择哪个 Java XML API?

javascript - SVG 自定义圆形