使用networkx导入图的布局位置

0 投票
1 回答
782 浏览
提问于 2025-04-17 07:47

我刚接触Networkx,想要导入通过random_layout()函数生成的布局位置,但不知道该怎么做。

生成布局位置的代码:

G = nx.random_geometric_graph(10, 0.5)
pos = nx.random_layout(G)
nx.set_node_attributes(G, 'pos', pos)
f = open("graphLayout.txt", 'wb')
f.write("%s" % pos)
f.close()
print pos
filename = "ipRandomGrid.txt"
fh = open(filename, 'wb')
nx.write_adjlist(G, fh)
#nx.write_graphml(G, sys.stdout)
nx.draw(G)
plt.show()
fh.close()

文件名:ipRandomGrid.txt

# GMT Tue Dec 06 04:28:27 2011
# Random Geometric Graph
0 1 3 4 6 8 9 
1 3 4 6 8 9 
2 4 7 
3 8 6 
4 5 6 7 8 
5 8 9 6 7 
6 7 8 9 
7 9 
8 9 
9 

我把节点的adjlist和布局都存储在文件里。现在我想用另一个文件中的相同布局和adjlist来生成图形。我尝试用下面的代码来生成,但不知道哪里出错了。有没有人能帮我看看问题出在哪里?

导入时的代码:

伪代码
G = nx.Graph() 
G = nx.read_adjlist("ipRandomGrid.txt")
# load POS value from file 
nx.draw(G)
nx.draw_networkx_nodes(G, pos, nodelist=['1','2'], node_color='b')
plt.show()

1 个回答

0

nx.random_layout 这个函数会返回一个字典,这个字典把节点和它们的位置对应起来。因为 pos 是一个 Python 对象,所以你不应该像这样把它的字符串版本直接存到文件里:f.write("%s" % pos)。这样做虽然能把字典存到文件里,但再读回来就麻烦了。

更好的做法是使用一些标准库中的模块来“序列化” pos,也就是把它转换成一种可以方便存储和读取的格式,比如 jsonpickle。这两个模块的使用方法基本相同,所以我这里就用 pickle 来演示一下。存储的代码是:

with open("graphLayout.txt", 'wb') as f:
    pickle.dump(pos, f)

重新加载的代码是:

with open("graphLayout.txt", 'rb') as f:
    pos = pickle.load(f)

撰写回答