对于read_edgelist,您假设您已经存在一个边缘列表。但是,您提供的是节点 + 属性。
由于您从具有文件格式(在您的 cmets 中说明)的文件开始,因此第一个挑战是将其转换为易于解析的格式。出于这个原因,我建议使用 CSV 文件格式。要对您的文件执行此操作,我将启动终端(Linux 和 Mac)cd 进入您的文件所在目录,然后运行以下两个命令:
sed -n 's/ : /,/gpw nodes_replaced1.txt' nodes.txt
这将读取nodes.txt(或您的文件),将所有出现的:(包括空格)替换为,,并将其保存为nodes_replaced1.txt。您可以随意更改文件名。
完成后,在终端中运行以下命令
sed -n 's/ /,/gwp nodes.csv' nodes_replaced1.txt
这将做类似的事情,除了读取nodes_replaced1.txt,将[spaces]替换为,,并将其写入CSV文件。
一旦您有了 CSV 文件,我建议您使用 Pandas 打开 CSV 文件并执行以下操作以将节点添加到您的图表中:
In [1]: import pandas as pd
In [2]: import networkx as nx
In [5]: nodes = pd.read_csv('nodes.csv', header=None)
In [6]: nodes
Out[6]:
0 1 2
0 0 52.88 52.53
1 1 56.63 49.53
2 2 38.60 69.81
3 3 43.00 2.88
In [7]: G = nx.Graph()
In [8]: G
Out[8]: <networkx.classes.graph.Graph at 0x105e94cd0>
In [9]: for row in nodes.iterrows():
...: G.add_node(row[1][0], x=row[1][1], y=row[1][2])
...:
In [10]: G.nodes(data=True)
Out[10]:
[(0.0, {'x': 52.880000000000003, 'y': 52.530000000000001}),
(1.0, {'x': 56.630000000000003, 'y': 49.530000000000001}),
(2.0, {'x': 38.600000000000001, 'y': 69.810000000000002}),
(3.0, {'x': 43.0, 'y': 2.8799999999999999})]
您会注意到,当我只调用G.nodes() 时,没有x & y 位置数据。但是,当我调用G.nodes(data=True) 时,会合并 x 和 y 位置数据。
有关如何创建图表以及如何放入与任何节点、边或图表关联的“属性”的更多信息,请参阅此页面:http://networkx.github.io/documentation/latest/tutorial/tutorial.html#nodes
最后,如果@Aric 出现回答这个问题,如果我错了,请纠正我!