d3 v4 dynamic graph

by Lukasz Guminski

HTML

<script src="https://d3js.org/d3.v4.min.js"></script>

CSS

line {
  stroke: #666;
}

.node {
  pointer-events: all;
}

circle {
  stroke: none;
  stroke-width: 40px;
}

.node text {
  font: 8px sans-serif;
}

JavaScript

var graph = new MyGraph();

setInterval(dynamicAddNodes, 1000);

function dynamicAddNodes() {
  var node = "UK";
  graph.removeNode(node);
  graph.addNode(node);
  graph.addLink("France", node);
}

function MyGraph() {

  var graph = {
    "nodes": [{
      "id": "France",
      "group": 1
    }, {
      "id": "Austria",
      "group": 1
    }, {
      "id": "Germany",
      "group": 1
    }, {
      "id": "The Netherlands",
      "group": 1
    }, {
      "id": "Italy",
      "group": 1
    }, {
      "id": "Switzerland",
      "group": 8
    }],
    "links": [{
      "source": "Austria",
      "target": "France",
      "value": 1
    }, {
      "source": "Germany",
      "target": "France",
      "value": 8
    }, {
      "source": "The Netherlands",
      "target": "France",
      "value": 10
    }, {
      "source": "The Netherlands",
      "target": "Germany",
      "value": 6
    }, {
      "source": "Italy",
      "target": "France",
      "value": 1
    }]
  };

  this.addNode = function(id) {
    graph.nodes.push({
      "id": id,
      "group": 1
    });
    update();
  }

  this.removeNode = function(id) {
    var i = 0;
    var n = findNode(id);
    while (i < graph.links.length) {
      if ((graph.links[i]['source'] === n) || (graph.links[i]['target'] == n)) graph.links.splice(i, 1);
      else i++;
    }
    var index = findNodeIndex(id);
    if (index !== undefined) {
      graph.nodes.splice(index, 1);
      update();
    }
  }

  this.addLink = function(sourceId, targetId) {
    var sourceNode = findNode(sourceId);
    var targetNode = findNode(targetId);

    if ((sourceNode !== undefined) && (targetNode !== undefined)) {
      graph.links.push({
        "source": sourceNode,
        "target": targetNode,
        "value": 1
      });
      update();
    }
  }

  var findNode = function(id) {
    for (var i = 0; i < graph.nodes.length; i++) {
      if (graph.nodes[i].id === id)
        return graph.nodes[i]
    };
  }

  var findNodeIndex =...