2017-06-16 64 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