I was looking for something similar to igraph’s erdos.renyi.game(n, p.or.m)
that would allow me to create a random network graph and export it as a json file with the following format.
{ "nodes":[ {"name":0}, {"name":1}, {"name":2} ], "links":[ {"source":0,"target":1}, {"source":1,"target":2}, {"source":2,"target":0} ] }
Unfortunately I could’t fing anything, so I wrote the following python script that does just that
from random import choice # start with the number of edges and nodes int_edges = 10 int_nodes = 10 # location of output file str_output_file = 'output.json' range_edges = range(0,int_edges) range_nodes = range(0,int_nodes) # a function to build and print the links def createLink(int_from,int_to): str_from = '\t\t{"source":%d' % int_from str_to = '"target":%d}' % int_to str_output = ','.join([str_from,str_to]) return str_output # a function to make sure we have no loops def nodesToString(int_from_node,int_to_node): if int_from_node != int_to_node: str_output_link = createLink(int_from_node,int_to_node) return str_output_link else: if int_from_node==(int_nodes-1): str_output_link = createLink(int_from_node-1,int_to_node) return str_output_link else: str_output_link = createLink(int_from_node+1,int_to_node) return str_output_link # open file for writing file_w_output=open(str_output_file,'w') # start the node section file_w_output.write('{\n\t"nodes":[\n') # print nodes for n in range_nodes: str_node_line = '\t\t{"name":%d}' % n if n==int_nodes-1: file_w_output.write(str_node_line+'\n\t],\n') else: file_w_output.write(str_node_line+',\n') # start the links section file_w_output.write('\t"links":[\n') # print links for i in range_edges: int_from_node = choice(range_nodes) int_to_node = choice(range_nodes) str_link = nodesToString(int_from_node,int_to_node) if i == int_edges-1: file_w_output.write(str_link+'\n\t]\n}') else: file_w_output.write(str_link+',\n') # close files file_w_output.close()
One reply on “Random d3js Network Graph – Python & d3js”
Or else:
import json
import networkx as nx
from networkx.readwrite import json_graph
G= nx.random_regular_graph(2,10)
for n in G:
G.node[n][‘name’] = n
d = json_graph.node_link_data(G)
json.dump(d, open(‘network.json’,’w’))