使用NetworkX将图形导出到具有节点位置的graphml

时间:2015-03-07 01:43:38

标签: python graph matplotlib networkx graphml

我正在使用NetworkX 1.9.1。

我有一个图表,我需要组织职位,然后我导出到graphml格式。

我在this question尝试过代码。它不起作用,这是我的例子

import networkx as nx
import matplotlib.pyplot as plt

G = nx.read_graphml("colored.graphml")

pos=nx.spring_layout(G) # an example of quick positioning
nx.set_node_attributes(G, 'pos', pos)

nx.write_graphml(G, "g.graphml")

nx.draw_networkx(G, pos)
plt.savefig("g.pdf")

以下是我得到的错误,问题是如何保存位置(graphml不接受数组)。

C:\Anaconda\python.exe C:/Users/sturaroa/Documents/PycharmProjects/node_labeling_test.py
Traceback (most recent call last):
  File "C:/Users/sturaroa/Documents/PycharmProjects/node_labeling_test.py", line 11, in <module>
    nx.write_graphml(G, "g.graphml")
  File "<string>", line 2, in write_graphml
  File "C:\Anaconda\lib\site-packages\networkx\utils\decorators.py", line 220, in _open_file
    result = func(*new_args, **kwargs)
  File "C:\Anaconda\lib\site-packages\networkx\readwrite\graphml.py", line 82, in write_graphml
    writer.add_graph_element(G)
  File "C:\Anaconda\lib\site-packages\networkx\readwrite\graphml.py", line 350, in add_graph_element
    self.add_nodes(G,graph_element)
  File "C:\Anaconda\lib\site-packages\networkx\readwrite\graphml.py", line 307, in add_nodes
    self.add_attributes("node", node_element, data, default)
  File "C:\Anaconda\lib\site-packages\networkx\readwrite\graphml.py", line 300, in add_attributes
    scope=scope, default=default_value)
  File "C:\Anaconda\lib\site-packages\networkx\readwrite\graphml.py", line 288, in add_data
    '%s as data values.'%element_type)
networkx.exception.NetworkXError: GraphML writer does not support <type 'numpy.ndarray'> as data values.

我的印象是我最好将位置定义为2个单独的节点属性x和y,并分别保存它们,以graphml格式like this为每个属性定义一个键。

但是,我对Python并不熟悉,并希望在我来回迭代之前想你的意见。

感谢。

1 个答案:

答案 0 :(得分:5)

你是对的,GraphML想要更简单的属性(没有numpy数组或列表)。

您可以将节点的x和y位置设置为此属性

G = nx.path_graph(4)
pos = nx.spring_layout(G)

for node,(x,y) in pos.items():
    G.node[node]['x'] = float(x)
    G.node[node]['y'] = float(y)

nx.write_graphml(G, "g.graphml")