d3.js:“手动定义强制布局的节点和链接时,无法读取未定义的属性'权重'

时间:2012-07-06 07:46:31

标签: graphics graph d3.js force-layout

我尝试以这种方式同时设置节点和链接:

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合作?

我正在阅读文档,显然源和目标必须是节点数组中节点的INDEXES。反正有改变吗?那么,我可以使用节点的名称而不是它在数组中的索引吗?

6 个答案:

答案 0 :(得分:18)

之前遇到同样的问题,这是由于链接的源/目标中存在空值。 打印节点链接信息可能有助于调试

答案 1 :(得分:11)

除了在链接的源/目标中提及null的答案之外,其原因可能是分配超出范围的源/目标。例如。你有10个节点,你将目标指定为第11个索引节点。

答案 2 :(得分:10)

力导向布局使用边权重来计算布局。尝试为所有连接添加虚拟"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源代码中)使用任何属性/类型。

答案 3 :(得分:10)

感谢上面的答案,它们引用了空源或目标值!

我一直在测试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();

答案 4 :(得分:5)

我认为您的源和目标中可能包含空值。我也有这个错误并通过过滤掉空值来修复它。

答案 5 :(得分:2)

我已经通过多种方式弹出了这个问题。最近,我的边缘列表如下:

{Source: 0; Target: 1}

而不是:

{source: 0, target: 1}