簡體   English   中英

使用 pygraphviz_layout 時出現“KeyError: Node not in graph”,即使節點在 networkx 圖中

[英]"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不同的任意(可散列)節點networkx 因此,上面的代碼在調用布局之前簡單地將節點標簽轉換為int並恢復節點和pos dict 中的更改。

我發現使用任意可散列節點不適用於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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM