"Leaf-justify" D3 tree graphs?

时间:2016-07-11 19:20:55

标签: javascript d3.js

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:

before

and have it come out similar to:

after

1 个答案:

答案 0 :(得分:3)

一种方法是发现树的深度,并将没有任何子节点的每个节点的depth属性设置为该值。

假设您的树数据如下:

var data = [
    {
        "name": "Top Level",
        "parent": "null",
        "children": [
            {
                "name": "Level 2: A",
                "parent": "Top Level",
                "children": [ ...

您使用以下方法创建了一棵树:

var tree = d3.layout.tree();

您可以通过在每个节点中搜索depth的最大值来获取树的depth

var treeDepth = d3.max(tree(data[0]), function(d) { return d.depth; });

完成后,每次重新计算树形布局时都可以重置它:

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
});

这适用于您的示例中布置的树(从左到右)。对于自上而下的布局,您必须改为d.x

以下是 JSFiddle ,其中包含一个改编自 this example 的工作解决方案。