DEV Community

Cover image for Creating a network graph using nodes and links(loop) D3
aroub72
aroub72

Posted on

Creating a network graph using nodes and links(loop) D3

I am trying to plot a network graph using nodes and links.
so far I was able to plot the nodes only.

Nodes graph:

to draw the links between those nodes I have to iterate through the data to extract the nodes location. Below is a sample of the data:

"links": [
    {"node01": "site05", "node02": "site08", "amount": 10},
    {"node01": "site05", "node02": "site02", "amount": 120},
    {"node01": "site05", "node02": "site03", "amount": 50},
    {"node01": "site05", "node02": "site07", "amount": 80},
    {"node01": "site05", "node02": "site09", "amount": 210},
    {"node01": "site05", "node02": "site10", "amount": 350}]

"nodes": [
    {
      "id": "site09",
      "x": 317.5,
      "y": 282.5
    },
    {
      "id": "site01",
      "x": 112,
      "y": 47
    },
    {
      "id": "site03",
      "x": 69.5,
      "y": 287
    }]

I tried using a for loop but I don't think my approach is correct.

window.onload = function(){
var svgCanvas = d3.select("svg") //setting up the canvas
.attr("width", 960) 
.attr("height", 540) 
.attr("class", "svgCanvas");


    d3.json("map.json", function(data) {
        console.log(data);

 svgCanvas.selectAll("circle.nodes")
        .data(data.nodes).enter() 
        .append("circle") 
        .append("svg:circle")
        .attr("cx", function(data){
            return data.x;})
        .attr("cy", function(data){
            return data.y;})
        .attr("r", 10);

var myMap=new Map();
myMap.set(links.data,nodes.data);
for (var [key,value] of myMap){
    console.log(key+'='+value);
}
    })
}

Top comments (0)