Method to save networkx graph to json graph?

2019-02-03 01:38发布

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?

5条回答
男人必须洒脱
2楼-- · 2019-02-03 02:10

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
查看更多
放我归山
3楼-- · 2019-02-03 02:14

Are the nodes and edges enough information? If so, you could write your own function:

json.dumps(dict(nodes=graph.nodes(), edges=graph.edges()))
查看更多
三岁会撩人
4楼-- · 2019-02-03 02:16

Generally I use the following code :

import networkx as nx; 
from networkx.readwrite import json_graph;
G = nx.Graph();
G.add_node(...)
G.add_edge(...)
....
json_graph.node_link_data(G)

it will create json formatted graph in which the nodes are in nodes and edges in links in addition to other information about the graph (directionality, ... etc)

查看更多
Fickle 薄情
5楼-- · 2019-02-03 02:27

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.

查看更多
孤傲高冷的网名
6楼-- · 2019-02-03 02:28

Try this:

# Save graph
nx.write_gml(G, "path_where_graph_should_be_saved.gml")

# Read graph
G = nx.read_gml('path_to_graph_graph.gml')
查看更多
登录 后发表回答