d3.js: “Cannot read property 'weight' of undefined” when manually defining both nodes and links for force layout

前端 未结 6 629
旧时难觅i
旧时难觅i 2020-12-09 16:31

I tried setting both nodes and links at the same time this way:

var force = d3.layout.force()
    .size([w, h])
    .nodes(nodes)
    .links(connections)
            


        
相关标签:
6条回答
  • 2020-12-09 17:13

    In addition to the answers mentioning the null in the source/target of links, the reason for this could be the assignment of an out-of-range source/target. E.g. you have 10 nodes and you assign the target to be the 11-th indexed node.

    0 讨论(0)
  • 2020-12-09 17:20

    I've had this issue pop up in a number of ways. Most recently, I had my edge list as follows:

    {Source: 0; Target: 1}
    

    instead of:

    {source: 0, target: 1}
    
    0 讨论(0)
  • 2020-12-09 17:21

    The force-directed layout uses edge weights to calculate the layout. Try adding a dummy "weight":1 to all of your connections.

    The code that initializes the links looks like this:

    links.forEach(function(d) {
        if (typeof d.source == "number") { d.source = nodes[d.source]; }
        if (typeof d.target == "number") { d.target = nodes[d.target]; }
    });
    

    Presumably you could tweak that (in the d3 source) to use any property/type.

    0 讨论(0)
  • 2020-12-09 17:31

    I think you might have null values in your source and target. I had this bug too and fixed it by filtering out the null values.

    0 讨论(0)
  • 2020-12-09 17:32

    I encounter same problem before, it is due to there is null values in source/target of links. print out nodes and links information might help to debug

    0 讨论(0)
  • 2020-12-09 17:32

    Thanks to the answers above which refer to null source or target values!

    I've been testing out the graph from http://bl.ocks.org/mbostock/4062045, and found that my data referenced a missing node.

    This may help others debug this issue:

    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();
    
    0 讨论(0)
提交回复
热议问题