如何解决使用pygraphviz_layout时出现“ KeyError:节点不在图中”,即使节点位于networkx图形中
我有一个由边列表组成的DataFrame network_df
G = nx.from_pandas_edgelist(network_df,source='Parent Node',target= 'Child Node',create_using=nx.DiGraph())
我正在使用pygraphviz_layout
计算G
中每个节点的位置
pos = pygraphviz_layout(G,prog="dot",args='-Gnodesep=10-Goverlap=false')
但这会引发以下错误:
Exception has occurred: KeyError
Traceback (most recent call last):
File "C:\..\Python37\lib\site-packages\pygraphviz\agraph.py",line 1615,in __new__
nh = gv.agnode(graph.handle,n.encode(graph.encoding),_Action.find)
KeyError: 'agnode: no key'
During handling of the above exception,another exception occurred:
Traceback (most recent call last):
File "<string>",line 1,in <module>
File "C:\...\Python37\lib\site-packages\networkx\drawing\nx_agraph.py",line 293,in pygraphviz_layout
node = pygraphviz.Node(A,n)
File "C:\...\Python37\lib\site-
packages\pygraphviz\agraph.py",line 1617,in __new__
raise KeyError("Node %s not in graph." % n)
KeyError: "Node ('','','A /// Standard','Event A') not in graph."
但是当我这样做
key = ('','Event A')
print(key in G.nodes())
这将显示True
,这意味着该节点确实在图中,在这里我该怎么做?
此外,如果我使用其他一些功能来计算位置,那么它会起作用
pos = nx.spring_layout(G)
这是怎么了?对于其他数据集,pygraphviz_layout
之前没有任何问题。
解决方法
以下方法应该起作用:
import networkx as nx
# an example graph with string (names) as nodes
g = nx.les_miserables_graph()
labels_to_int = {}
int_to_labels = {}
for i,label in enumerate(g):
labels_to_int[label] = i
int_to_labels[i] = label
# update labels to ints with
nx.relabel_nodes(g,labels_to_int,copy=False)
print(g.nodes)
# Tested only with the following since I have pygraphviz not installed
pos = nx.kamada_kawai_layout(g)
# pos = pygraphviz_layout(G,prog="dot",args='-Gnodesep=10-Goverlap=false')
# changes back to original labels
nx.relabel_nodes(g,int_to_labels,copy=False)
label_pos = {label: pos[labels_to_int[label]] for label in g}
print(label_pos)
# {'Napoleon': array([0.73407672,0.66096404]),'Myriel': array([0.67744174,0.53499379]),....
print(g.nodes)
# ['Napoleon','Myriel',...
背景
出现错误的原因可能是pygraphviz
不能与networkx
一起用于任意(可哈希)节点。因此,以上代码仅在调用布局之前将节点标签强制转换为int
并还原节点和pos
字典中的更改。
我发现使用任意可散列的节点不适用于 dataPath = QtCore.QStandardPaths.writableLocation(AppLocalDataLocation)
dataPathDir = QtCore.QDir(dataPath)
if not dataPathDir.exists():
# create the directory (including parent directories if they don't exist);
# that the argument of mkpath is relative to the QDir's object path,so
# using '.' means that it will create the actual dataPath
dataPathDir.mkpath('.')
后端,但可以用于pygraphviz
:
pydot
这里的重点是从import networkx as nx
from networkx.drawing.nx_pydot import graphviz_layout
g = ...
pos = graphviz_layout(g,"dot")
nx.draw_networkx(g,pos=pos)
而不是graphviz_layout
或其他地方导入networkx.drawing.nx_pydot
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。