[英]How to choose root node in "dot" graph layout for plotting with networkx and pydot/pygraphviz
[英]"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.