将networkx图保存到json图的方法?

xxhby3vn  于 2023-05-23  发布在  其他
关注(0)|答案(7)|浏览(206)

似乎networkx中应该有一个方法来导出json图形格式,但我没有看到它。我想用nx.to_dict_of_dicts()应该很容易做到,但需要一些操作。有人知道一个简单而优雅的解决方案吗?

p1tboqfb

p1tboqfb1#

documentation包含完整说明
一个简单的例子是:

import networkx as nx
from networkx.readwrite import json_graph

DG = nx.DiGraph()
DG.add_edge('a', 'b')
print json_graph.dumps(DG)

您还可以查看Javascript/SVG/D3示例,该示例很好地将物理特性添加到图形可视化中。

cnwbcb6i

cnwbcb6i2#

通常我使用以下代码:

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)

它将创建JSON格式的图,其中节点在nodes中,边在links中,以及关于图的其他信息(方向性,…等)

eeq64g8w

eeq64g8w3#

下面是我刚才做的一个JSON方法,以及读取结果的代码。它保存节点和边属性,以防您需要。

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
s4chpxco

s4chpxco4#

试试这个:

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

# Read graph
G = nx.read_gml('path_to_graph_graph.gml')
yruzcnhs

yruzcnhs5#

节点和边的信息是否足够?如果是这样,你可以写自己的函数:

json.dumps(dict(nodes=graph.nodes(), edges=graph.edges()))
3hvapo4f

3hvapo4f6#

其余的解决方案对我不起作用。networkx 2.2文档:

nx.write_gpickle(G, "test.gpickle")
G = nx.read_gpickle("test.gpickle")
nlejzf6q

nlejzf6q7#

以下是亚伯拉罕·弗拉克斯曼对networkx 2.7的回答的修改版本:

def save(G, fname):
    nodeArr = []
    for node in list(G.nodes(data=True)):
        print('node:', node)
        nodeArr.append(node)

    edgeArr = []
    for edge in list(G.edges()):
        print('edge:', edge)
        edgeArr.append(edge)

    graphDict = { 'nodes': nodeArr,
                  'edges': edgeArr}
    json.dump(graphDict, 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

相关问题