2012-07-06 74 views
17

我試圖在同一時間這樣設定兩個節點和鏈接:d3.js:「不能讀取屬性‘重’的未定義」手動定義節點和鏈接時力佈局

var force = d3.layout.force() 
    .size([w, h]) 
    .nodes(nodes) 
    .links(connections) 
    .start(); 

nodes = [{"name":"data_base_id", "kind":"subgenre"},...] 
connections = [{"source":"name_of_node", "target":"name_of_other_node"},...] 

我有數據可能沒有連接,所以有必要定義這些節點,以便所有節點都得到渲染。定義流派很簡單。 但我得到這個錯誤;

Cannot read property 'weight' of undefined 

當我註釋掉.links(連接)的圖形渲染(伸出一束點散落各處......)我如何獲得的連接/鏈路與D3進行合作?

我正在讀的文檔,顯然,源和目標必須是節點陣列中的節點索引。無論如何要改變這一點?那麼,我可以使用節點的名稱而不是數組中的索引?

回答

8

強制定向佈局使用邊權來計算佈局。嘗試添加一個虛擬"weight":1到您的所有連接。

初始化鏈接的代碼如下所示:

links.forEach(function(d) { 
    if (typeof d.source == "number") { d.source = nodes[d.source]; } 
    if (typeof d.target == "number") { d.target = nodes[d.target]; } 
}); 

想必你可以調整的是(在D3源)使用任何屬性/類型。

4

我想你可能在你的源和目標空值。我也有這個bug,並通過濾除空值來修復它。

16

我以前遇到同樣的問題,這是由於存在鏈接源/目標空值。 打印出來節點鏈接信息可能有助於調試

1

我有這個問題在許多方面彈出。最近,我有我的優勢名單如下:

{Source: 0; Target: 1} 

代替:

{source: 0, target: 1} 
10

除了答案提的鏈接的源/目標空,這樣做的原因可能是指定超出範圍的源/目標。例如。你有10個節點,你指定目標爲第11個索引節點。

+0

我有這個問題,我該如何去不扔的錯誤,如果我無法找到我的數據的節點? – thatOneGuy 2015-09-17 12:33:51

+0

@air_bob表示,如果任何鏈接分配超出節點數量,則可以打印出來 – elachell 2015-11-24 00:49:15

+0

重要提示:JavaScript索引爲0。所以我相信正確的評論是「..你有10個節點,並指定目標(或源)是第10個索引節點」 – JHowIX 2016-06-07 18:42:05

9

感謝上面提到的空值或目標值的答案!

我已經從http://bl.ocks.org/mbostock/4062045檢驗出圖,並發現我引用的數據丟失節點。

這可以幫助別人調試這個問題:

d3.json("my-buggy-data.json", function(error, graph) { 

    // Find blank links, which give the error 
    // "Uncaught TypeError: Cannot read property 'weight' of undefined" 
    graph.links.forEach(function(link, index, list) { 
     if (typeof graph.nodes[link.source] === 'undefined') { 
      console.log('undefined source', link); 
     } 
     if (typeof graph.nodes[link.target] === 'undefined') { 
      console.log('undefined target', link); 
     } 
    }); 

    force 
     .nodes(graph.nodes) 
     .links(graph.links) 
     .start(); 
+1

這解決了我的問題,謝謝! – 2016-04-14 11:43:35

相關問題