Network Diagram with Sigma.js

This example uses sigma.js to visualize a network produced in python.

Notebook Config


In [1]:
from IPython.core.display import display, HTML
from string import Template
import pandas as pd
import json, random

In [2]:
HTML('''
<script src="lib/sigmajs/sigma.min.js"></script>
<script src="js/sigma-add-method-neighbors.js"></script>
''')


Out[2]:

Network Construction


In [3]:
random.seed(42)

n_nodes = 40
n_edges = 200

graph_data = { 'nodes': [], 'edges': [] }

for i in range(n_nodes):
    graph_data['nodes'].append({
            "id": "n" + str(i),
            "label": "n" + str(i),
            "x": random.uniform(0,1),
            "y": random.uniform(0,1),
            "size": random.uniform(0.2,1)
        })

for j in range(n_edges):
    x_center = random.uniform(0,1)
    y_center = random.uniform(0,1)
    x_dist = random.uniform(0.1,0.5)
    y_dist = random.uniform(0.2,0.5)
    neighborhood = []
    for node in graph_data['nodes']:
        if abs(node['x'] - x_center) < x_dist:
            if abs(node['y'] - y_center) < y_dist:
                neighborhood.append(int(node['id'].replace('n','')))
    if len(neighborhood) >= 2:
        ends = random.sample(neighborhood,2)
        graph_data['edges'].append({
                "id": "e" + str(j),
                "source": "n" + str(ends[0]),
                "target": "n" + str(ends[1])
            })

In [4]:
pd.DataFrame(graph_data['nodes']).head()


Out[4]:
id label size x y
0 n0 n0 0.420023 0.639427 0.025011
1 n1 n1 0.741360 0.223211 0.736471
2 n2 n2 0.537537 0.892180 0.086939
3 n3 n3 0.604284 0.029797 0.218638
4 n4 n4 0.719908 0.026536 0.198838

In [5]:
pd.DataFrame(graph_data['edges']).head()


Out[5]:
id source target
0 e0 n5 n12
1 e1 n25 n1
2 e2 n10 n20
3 e3 n6 n29
4 e4 n15 n17

Visualization


In [6]:
js_text_template = Template(open('js/sigma-graph.js','r').read())

js_text = js_text_template.substitute({'graph_data': json.dumps(graph_data),
                                       'container': 'graph-div'})

html_template = Template('''
<div id="graph-div" style="height:400px"></div>
<script> $js_text </script>
''')
HTML(html_template.substitute({'js_text': js_text}))


Out[6]:

Note that you can zoom and pan (click and move) to navigate the graph. Also note that if you click on a node, it highlights it and the nodes to which it is directly connected, along with all of the edges within this neighborhood.