简体   繁体   English

“叶对齐” D3树形图?

[英]“Leaf-justify” D3 tree graphs?

What do I need to do to get tree graphs to render such that nodes are justified towards the leaf side of the graph? 我需要做些什么来使树图呈现出来,使节点朝向图的叶侧对齐?

I'd like to take an arbitrary tree graph that might normally look like: 我想拍摄一个通常看起来像这样的任意树形图:

之前

and have it come out similar to: 并使其类似于:

后

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. 一种实现方法是发现树的深度,并将没有任何子节点的每个节点的depth属性设置为该值。

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 : 你可以得到depth通过搜索的最大值每个节点树的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. 对于自上而下的布局,您必须改为dx

Here is a JSFiddle with a working solution adapted from this example . 这是一个JSFiddle,其中有一个适用于此示例可行解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM