2017-03-09 124 views

回答

3

我適應從我以前的答案在這裏下面的代碼: Collapsible D3 force directed graph with non-tree data

在小提琴這裏

完整代碼:https://jsfiddle.net/sheilak/jfwkx4f3/

我添加的屬性到節點來跟蹤他們是否倒塌,有多少他們的父節點被摺疊。此外,無論它們是否可摺疊 - 源節點不應該是可摺疊的,因爲該庫似乎不喜歡沒有鏈接的圖形。

graph.nodes.forEach(function (d, i) { 
    graph.nodes[i] = { "name": d }; 
    graph.nodes[i].collapsing = 0; // count of collapsed parent nodes 
    graph.nodes[i].collapsed = false; 
    graph.nodes[i].collapsible = false; 
}); 

我改變了鏈接的代碼,指向整個源或目標節點而不是索引,因爲我們需要源節點進行過濾。我還設置了所有目標節點都可摺疊。

graph.links.forEach(function(e) { 
    e.source = graph.nodes.filter(function(n) { 
     return n.name === e.source; 
     })[0], 
    e.target = graph.nodes.filter(function(n) { 
     return n.name === e.target; 
     })[0]; 
    e.target.collapsible = true; 
}); 

我把佈局代碼拉出來放到一個函數中,這樣我們就可以在每次單擊節點時調用它。我還添加了代碼,根據每個圖表節點和鏈接是否摺疊來過濾圖形節點和鏈接。

update(); 

var nodes, links; 

function update() { 
    nodes = graph.nodes.filter(function(d) { 
    // return nodes with no collapsed parent nodes 
    return d.collapsing == 0; 
    }); 

    links = graph.links.filter(function(d) { 
    // return only links where source and target are visible 
    return d.source.collapsing == 0 && d.target.collapsing == 0; 
    }); 

    // Sankey properties 
    sankey 
    .nodes(nodes) 
    .links(links) 
    .layout(32); 

    // I need to call the function that renders the sakey, remove and call it again, or the gradient coloring doesn't apply (I don't know why) 
    sankeyGen(); 
    svg.selectAll("g").remove(); 
    sankey.align("left").layout(32); 
    sankeyGen(); 
} 

我不得不註釋掉這一行,因爲它是與單擊處理程序的干擾,我不知道我已經改變了那裏。

.on("start", function() { 
    //this.parentNode.appendChild(this); 
}) 

我添加了一個點擊處理程序來執行摺疊。

node.on('click', click); 
function click(d) { 
    if (d3.event.defaultPrevented) return; 
    if (d.collapsible) { 
    // If it was visible, it will become collapsed so we should decrement child nodes count 
    // If it was collapsed, it will become visible so we should increment child nodes count 
    var inc = d.collapsed ? -1 : 1; 
    recurse(d); 

    function recurse(sourceNode){ 
     //check if link is from this node, and if so, collapse 
     graph.links.forEach(function(l) { 
     if (l.source.name === sourceNode.name){ 
      l.target.collapsing += inc; 
      recurse(l.target); 
     } 
     }); 
    } 
    d.collapsed = !d.collapsed; // toggle state of node 
    }  
    update(); 
} 
+1

我覺得這樣是因爲我沒有辦法足夠感謝你!我非常感謝你的工作來回答這個問題。我試過但我做不到,你的回答對我來說是一個巨大的教訓!謝謝。 – TheBiro

0

上面的提琴很適合每個孩子都有單親的標準樹。然而,對於傳統的sankey非常適合的多種血統('格子')場景,這個可摺疊的表示可能不太直截了當。例如,當展開節點A以顯示其子節點時,如果任何A的子節點具有其他未擴展的父節點,則父節點會自動擴展。這可能是你想要的,因爲只顯示部分血統會導致誤導,但無論如何它確實會讓你感到有點意外。迷失方向可以通過不重新居中節點來緩解。可能會出現意想不到的組合擴展效應,特別是對於高度網格化的數據結構。