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:
node1 | node2 | node3 | |
node1 | 0 | 8 | 1 |
node2 | 8 | 0 | 3 |
node3 | 1 | 3 | 0 |
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[target])} listLinks.append(dicOut) 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):
