data science

From adjacency matrix to d3js network graph

So yeah, I’m back in this.

Very simple script to turn an adjacency matrix to a D3js network json file.

This is the file that we start with:


As you can see, this is an undirected graph.

This next bit is the code I wrote for it.

import pandas as pd
import json

df = pd.read_csv('inputdata.csv', index_col=0)

listNodes = [{'id':x} for x in list(df.columns)]
listLinks = []

for i in range(0,len(listNodes)):
    for j in range(i+1, len(listNodes)):
        source = listNodes[i]['id']
        target = listNodes[j]['id']
        dicOut = {'source': source,
                  'target': target,
                  'weight': int(df[source][target])}


jsonOut = {'nodes':listNodes, 'links':listLinks}

with open('d3_network_graph.json', 'w') as fw:
    fw.write(json.dumps(jsonOut, indent=2))

Please note that I changed the Pandas datatype in line 16 to int so that JSON can recognise it when writing the output file. If you are using decimals you need to change it to a float.

Also, the indent=2 in line 23 is there to make the output readable to humans ∴ not necessary for D3JS.

This is what the output file looks like:

  "nodes": [
      "id": "node1"
      "id": "node2"
      "id": "node3"
  "links": [
      "source": "node1",
      "target": "node2",
      "weight": 8
      "source": "node1",
      "target": "node3",
      "weight": 1
      "source": "node2",
      "target": "node3",
      "weight": 3

Finally, this is what the network graph looks like (depending on your settings obviously):

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s