vis.js and a brief look at how to draw network topologies

Published 01-06-2017 06:50:55

In this blog post, I’d like to introduce the excellent vis.js JavaScript library which can be used to graph network topologies.

Example Graph

Below is an example graph generated from a traceroute data, which nicely shows a Clos topology.

JSON input

The format vis.js needs is quite simple. You pass a list of dicts called nodes, in each node you have an id (Unique ID) and a label (Display Text). Interconnects are described in a list of dicts called links, which is a to/from pairing of id (Referenced from nodes). A simple example joining

{
   "nodes" : [
      {
         "id" : 1,
         "label" : "R1"
      },
      {
         "id" : 2,
         "label" : "R2"
      },
   ],
   "links" : [
      {
         "from" : 1,
         "to" : 2
      }
   ]
}

Drawing an example graph

Drawing a graph with vis.js requires a few steps

  1. Get the JSON data into a dict of nodes and edges
  2. Create a directed graph
  3. Draw the graph with the JSON data, and the options

Sample Code here:

<script type="text/javascript" src="graph.json"></script>
<script type="text/javascript">

var parsed = JSON.parse(json);
    // create a network
    var container = document.getElementById("mynetwork");

    // provide the data in the vis format
    var data = {
      nodes: parsed.nodes,
      edges: parsed.links
    };
    var options = {
                layout: {
                    hierarchical: {
                        direction: "LR",
                        sortMethod: "directed",
                        levelSeparation: 200,
                        nodeSpacing: 40, 
                        randomSeed: 6
                    }
                },
                interaction: {
                    hover: true
                }
   };

    // initialize your network!
    var network = new vis.Network(container, data, options);
</script>