简体   繁体   中英

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 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM