"KeyError: Node not in graph" when using pygraphviz_layout even though node is in networkx graph

"KeyError: Node not in graph" when using pygraphviz_layout even though node is in networkx graph

我有一个 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 = ('', '', 'A /// Standard', '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 字典中的更改。

我发现使用任意可哈希节点不适用于 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)

这里的关键点是从 networkx.drawing.nx_pydot 而不是 networkx.drawing.nx_agraph 或其他地方导入 graphviz_layout