使用networkx导入图形的布局位置
我对 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()
I am very new to Networkx. I am trying to import layout position generated by random_layout()
function. I dont know how to do proceed with it.
Code to generate layout position:
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()
File: 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
I am storing both node adjlist
and the layout in files. Now I want to generate the graph with the same layout and adjlist
from other file. I tried to generate it with the below code. Can anyone help me to figure out what is wrong over here.
Code while importing:
Pseudo Code
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
nx.random_layout 函数返回将节点映射到位置的字典。由于 pos 是一个 Python 对象,您不希望只将其打印字符串版本存储到文件中,就像在 f.write("%s" % pos) 中所做的那样。这会为您提供一个包含字典的文件,但读回它并不那么容易。
相反,使用专为该任务设计的标准库模块之一序列化
pos
,例如json
或pickle
。它们的接口基本相同,因此我将仅展示如何使用pickle
来实现。存储为:重新加载为:
The
nx.random_layout
function returns a dictionary mapping nodes to positions. Aspos
is a Python object, you don't want to just store the printed string version of it to a file, as you did inf.write("%s" % pos)
. This gives you a file containing your dictionary, but reading it back in isn't as easy.Instead, serialize
pos
using one of the standard library modules designed for that task, for example,json
orpickle
. Their interfaces are basically the same, so I'll just show how to do it withpickle
. Storing is:Reloading is: