2015-10-15 33 views
0

我是新的d3js,我有一些問題試圖將csv文件映射到強制佈局的鏈接。爲什麼我的d3 map函數返回一個未定義的源屬性?

這是我的csv文件:

node,edges,centrality_degree 
1,"[(1, 2), (1, 3), (1, 4), (1, 5)]",1.0 
2,"[(2, 1), (2, 3), (2, 4), (2, 5)]",1.0 
3,"[(3, 1), (3, 2), (3, 4), (3, 5)]",1.0 
4,"[(4, 1), (4, 2), (4, 3), (4, 5)]",1.0 
5,"[(5, 1), (5, 2), (5, 3), (5, 4)]",1.0 

我想邊緣的值設置爲d3.layout.force(的鏈接屬性),映射值然而,當,我得到一個錯誤:

Uncaught TypeError: Cannot read property 'weight' of undefined

我不知道是否它是正確的返回一堆對象的數組,這就是我在控制檯上得到的。 5個數組,每個數組有4個對象,每個對象都有它的源和目標屬性。屬性都是正確的,除了5數組。我得到一個未定義的值,它的第一個源值。它應該是5

這裏是我的代碼:

var force = d3.layout.force() 
    .size([w, h]); 

d3.csv("{{ g }}", function(d) { 

    var nodes = d3.values(d.map(function(d){ return +d.node; })); 

    var links_list = d.map(function(d) { 

     list_array = JSON.parse(d.edges.replace(/\(/g,"[").replace(/\)/g,"]")); 

     var i, len = list_array.length; 

     links = []; 

     for (i=0; i<len; i++) { 
      links.push({source: list_array[i][0] ,target: list_array[i][1] }); 
     } 

     console.log(links); 

     #console result: 
     #[Object, Object, Object, Object] 
     #[Object, Object, Object, Object] 
     #[Object, Object, Object, Object] 
     #[Object, Object, Object, Object] 
     #expanding one array: 
      #0: Object 
      #1: Object 
      #2: Object 
      #3: Object 
     #[Object, Object, Object, Object] 
      #expanding the array[5][0] object: 
      #0: Object 
       #source: undefined 
       #target: 2 
       #__proto__: Object 

    }); 

    force 
     .nodes(nodes) 
     .links(links) 
     .start(); 

... 

}); 

什麼我做錯了,爲什麼我得到這個錯誤?

我感謝您的幫助。

+1

您指定爲鏈接的源和目標的數字應該是節點數組中的索引,而不是節點ID。它們從0開始,而不是從1開始。如果要使用ID,請參閱https://stackoverflow.com/questions/23986466/d3-force-layout-linking-nodes-by-name-instead-of-index –

+0

@LarsKotthoff,他們是數組的索引。數字0是控制檯上數組的第一項的引用。 –

+1

數據中的數字不是 - 它們從1開始,5個節點上升到5。 –

回答

1

The values of the source and target attributes should be specified as indexes into the nodes array; these will be replaced by references after the call to force start.

注意,數組的下標從0開始,而不是從1但是,在從CSV數據,您有一個像(5, 1), (5, 2), (5, 3), (5, 4)鏈接和您的節點陣列只有5個元素;最後一個元素的索引將爲4.您應該將這些數字減少爲1來表示實際節點。

例如:

var nodes = [{ name: "A", id: 1},{ name: "B", id: 2}]; 

力佈局期望的鏈接陣列,如下所示。

var links = [{ source:0, target: 1 }]; 

希望你有這個問題。你將不得不按照如下所示來獲得實際的指數。

for (i=0; i<len; i++) { 
    links.push({source: list_array[i][0]-1 ,target: list_array[i][1]-1 }); 
} 
相關問題