gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:57:23 41 4
gpt4 key购买 nike

我正在使用 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 不是很熟悉,在我来回迭代之前希望得到您的意见。

谢谢。

最佳答案

你是对的,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")

关于python - 使用 NetworkX 将图形导出到带有节点位置的 graphml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28910466/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com