Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to save networkx graph to json graph?

Seems like there should be a method in networkx to export the json graph format, but I don't see it. I imagine this should be easy to do with nx.to_dict_of_dicts(), but would require a bit of manipulation. Anyone know of a simple and elegant solution?

like image 435
Bob Avatar asked Jul 02 '10 02:07

Bob


People also ask

How is a graph stored in NetworkX?

In the networkx implementation, graph objects store their data in dictionaries. Nodes are part of the attribute Graph. node , which is a dictionary where the key is the node ID and the values are a dictionary of attributes. Edges are part of the attribute Graph.

How does NetworkX store data?

NetworkX uses dicts to store the nodes and neighbors in a graph.


2 Answers

This documentation contains a full description

A simple example is this:

import networkx as nx from networkx.readwrite import json_graph  DG = nx.DiGraph() DG.add_edge('a', 'b') print json_graph.dumps(DG) 

You can also take a look at the Javascript/SVG/D3 nice example on adding physics to the graph visualization.

like image 127
sw. Avatar answered Sep 22 '22 00:09

sw.


Here is a JSON approach that I just did, together with code to read the results back in. It saves the node and edge attributes, in case you need that.

import simplejson as json import networkx as nx G = nx.DiGraph() # add nodes, edges, etc to G ...  def save(G, fname):     json.dump(dict(nodes=[[n, G.node[n]] for n in G.nodes()],                    edges=[[u, v, G.edge[u][v]] for u,v in G.edges()]),               open(fname, 'w'), indent=2)  def load(fname):     G = nx.DiGraph()     d = json.load(open(fname))     G.add_nodes_from(d['nodes'])     G.add_edges_from(d['edges'])     return G 
like image 21
Abraham Flaxman Avatar answered Sep 22 '22 00:09

Abraham Flaxman