Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json representation for d3 force directed networks

I am trying to make a network visualisation of RISK. You can view it with the required code at http://bl.ocks.org/4683850.

The visualisation works but it required a lot of manual labor. I manually adapted the json file such that the connections were of the following shape:

{
    "source": 1,
    "target": 0,
    "value": 5
} 

What would one need to do to the d3 code such that a connection is determined by the names of the nodes? The input would then be:

{
    "source": "WesternAustralia",
    "target": "NewGuinea",
    "value": 5
} 

Whenever I try that I get the following error:

Uncaught TypeError: Cannot call method 'push' of undefined 
like image 714
cantdutchthis Avatar asked Dec 21 '22 10:12

cantdutchthis


1 Answers

The D3 docs provide an explanation of how links work:

https://github.com/mbostock/d3/wiki/Force-Layout#wiki-links

In short, the array of links can either contain indices for source and target, which get remapped to objects from nodes, or they contain the references to the objects from nodes themselves. You need to remap your links' source and target to the objects from nodes.

Assuming your source and target properties are using names as shown in your second example above, you can add the follow snippet to the beginning of your d3.json callback to do the remapping:

    var nodeMap = {};
    graph.nodes.forEach(function(x) { nodeMap[x.name] = x; });
    graph.links = graph.links.map(function(x) {
      return {
        source: nodeMap[x.source],
        target: nodeMap[x.target],
        value: x.value
      };
    });
like image 98
Chris Pettitt Avatar answered Jan 06 '23 02:01

Chris Pettitt