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

Nul*_*uli 18 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"},...]
Run Code Online (Sandbox Code Playgroud)

我有可能没有连接的数据,因此有必要定义节点,以便渲染所有节点.定义类型非常简单.但是我得到了这个错误;

Cannot read property 'weight' of undefined
Run Code Online (Sandbox Code Playgroud)

当我评论出.links(连接)时,图形会呈现(突然出现一堆散布的点......)如何让连接/链接与d3合作?

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

air*_*bob 18

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


ela*_*ell 11

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


Zac*_*chB 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]; }
});
Run Code Online (Sandbox Code Playgroud)

大概你可以调整(在d3源代码中)使用任何属性/类型.


pti*_*tim 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();
Run Code Online (Sandbox Code Playgroud)


syn*_*kon 5

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