2015-11-01 51 views
5

我試圖訂購D3 sankey中的節點。我希望具有較大值的節點被繪製得更高。d3 sankey圖中的訂購節點

這是相關的代碼(based on d3 noob's code)片段,我嘗試使用D3的內置排序功能來實現我想要的功能。結果不是我所期望的。

在檢查sankey.js時,我不完全清楚插件如何訂購節點。任何建議的話題,將不勝感激。

//set up graph in same style as original example but empty 
    graph = {"nodes" : [], "links" : []}; 

    data.forEach(function (d) { 
     graph.nodes.push({ "name": d.source }); 
     graph.nodes.push({ "name": d.target }); 
     graph.links.push({ "source": d.source, 
      "target": d.target, 
      "value": +d.value }); 
    }); 

//try to sort the nodes and links before indexing them (not working) 
    graph.nodes.sort(function (a,b) {return d3.descending(a.value, b.value); }); 
    graph.links.sort(function (a,b) {return d3.descending(a.value, b.value); }); 

    // return only the distinct/unique nodes 
    graph.nodes = d3.keys(d3.nest() 
     .key(function (d) { return d.name; }) 
     .map(graph.nodes)); 

    // loop through each link replacing the text with its index from node 
    graph.links.forEach(function (d, i) { 
     graph.links[i].source = graph.nodes.indexOf(graph.links[i].source); 
     graph.links[i].target = graph.nodes.indexOf(graph.links[i].target); 
    }); 

    //now loop through each nodes to make nodes an array of objects 
    // rather than an array of strings 
    graph.nodes.forEach(function (d, i) { 
     graph.nodes[i] = { "name": d }; 
    }); 
+0

如果我正確地讀你的代碼 - 'graph.nodes.sort(功能(A,B){回報d3.descending(a.value中,b.value);});'節點做沒有價值的財產來排序... – Mark

+0

是的。我可能需要對sankey.js中的值進行排序。將在這裏嘗試發佈結果。 – seb

+0

@seb你找出解決方案嗎?如果是這樣,你可以發佈? – Danny

回答

4

卸下從resolveCollisions以下行()函數在sankey.js文件將從改變停止節點的順序:

function resolveCollisions() { 
    ... 
    // nodes.sort(ascendingDepth); // commented this out to prevent node reordering 
    ... 
} 

節點將被垂直地排列然而它們原本是人口稠密的。因此,如果您在推送數據之前先排序節點,它們將按排序順序顯示。

1

如果您將佈局iterations值設置爲零,您將按照字母順序(按名稱)順序獲取節點:這對我來說工作得很好。

var sankey = d3.sankey() 
    .nodeWidth(36) 
    .nodePadding(40) 
    .size([width, height]) 
    .layout(0); /* <<<<<<< setting the iterations to zero */