1

我正在尝试创建一个 Sankey 图,虽然我现在可以加载我的源代码,但我在sankey.js和我的 html 代码之间遇到了一个小问题。

当我运行 HTML 代码时,我收到如下错误消息: Uncaught TypeError: Cannot call method 'push' of undefined

这是错误链接将我指向的位置:

// 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 === "name") source = link.source = nodes[link.source];      
    if (typeof target === "name") target = link.target = nodes[link.target];      
    source.sourceLinks.push(link);      
    target.targetLinks.push(link);    
  });  
}

这是 HTML 代码中的输入(我的数据取自 csv 文件)。

//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
  });
});

我的问题是:sankey.js 是否依赖于我的数据来自 json 文件的假设?. 如果是这样,我该如何调整它以使其与 csv 文件兼容?数据保存为下面列出的 csv 文件:

source,target,value
Barry,Elvis,2
Frodo,Elvis,2
Frodo,Sarah,2
Barry,Alice,2
Elvis,Sarah,2
Elvis,Alice,2
Sarah,Alice,4
4

1 回答 1

0

您需要使用链接中存在的对象或链接中的nodes索引。看起来您正在为此使用 CSV 中的字符串,这将以您观察到的方式中断。nodes.source.target

要修复,请保留对您正在创建的对象的引用并在链接中使用它们:

data.forEach(function (d) {
      var source = { "name": d.source },
          target = { "name": d.target };
      graph.nodes.push(source);
      graph.nodes.push(target);
      graph.links.push({ "source": source,
                         "target": target,
                         "value": +d.value });
     });
于 2013-12-13T16:44:26.793 回答