2017-06-16 62 views
0

我想運行從bl.ocks.org一個熱平衡圖(http://bl.ocks.org/d3noob/c2637e28b79fb3bfea13)的例子中,但是當我熱平衡圖中D3

python -m SimpleHTTPServer 8888 & 

從文件夾將以index.html運行它, sankey.js和桑基-formatted.json在下面的行

source.sourceLinks.push(link); 

給出一個錯誤:

sankey.js:91TypeError: undefined is not an object (evaluating 'source.sourceLinks.push') 

功能這個代碼是從是:

links.forEach(function(link) { 
    var source = link.source, 
     target = link.target; 
    if (typeof source === "number") source = link.source = nodes[link.source]; 
    if (typeof target === "number") target = link.target = nodes[link.target]; 
    source.sourceLinks.push(link); 
    target.targetLinks.push(link); 
}); 

和我的JSON文件是:

{ 
"nodes": [ 
{ 
    "name": "Africa" 
}, 
{ 
    "name": "America" 
}, 
... 
], 
"links":[ 
{ 
    "source": "Africa", 
    "target": "America", 
    "value": 1 
}, 
{ 
    "source": "America", 
    "target": "Africa", 
    "value": 2 
}, 
... 
]} 

回答

0
// Populate the sourceLinks and targetLinks for each node. 
    // Also, if the source and target are not objects, assume they are indices. 
    function computeNodeLinks() { 
    nodes.forEach(function(node) { 
     node.sourceLinks = []; 
     node.targetLinks = []; 
    }); 
    links.forEach(function(link) { 
     var source = link.source, 
      target = link.target; 
     if (typeof source === "number") source = link.source = nodes[link.source]; 
     if (typeof target === "number") target = link.target = nodes[link.target]; 
     source.sourceLinks.push(link); 
     target.targetLinks.push(link); 
    }); 
    } 

我認爲你缺少你的數據結構的東西。用這個改造過的數據再試一次。即node索引,這是需要設置的鏈接。

{ 
"nodes": [ 
    { 
    "node" : 0, 
    "name": "Africa" 
    }, 
    { 
    "node" :1, 
    "name": "America" 
    }, 
    { 
    "node" :2, 
    "name": "Europe" 
    } 
], 
"links":[ 
    { 
    "source": 0, 
    "target": 2, 
    "value": 1 
    }, 
    { 
    "source": 1, 
    "target": 2, 
    "value": 2 
    }, 
    { 
    "source": 0, 
    "target": 1, 
    "value": 1 
    } 
]} 

Plunker Example