簡體   English   中英

“葉對齊” D3樹形圖?

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

我需要做些什么來使樹圖呈現出來,使節點朝向圖的葉側對齊?

我想拍攝一個通常看起來像這樣的任意樹形圖:

之前

並使其類似於:

后

一種實現方法是發現樹的深度,並將沒有任何子節點的每個節點的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
});

這適用於示例中從左到右排列的樹木。 對於自上而下的布局,您必須改為dx

這是一個JSFiddle,其中有一個適用於此示例可行解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM