如何在networkx中正确添加和绘制边标签?

How to add and draw edge labels in networkx correctly?

我正在添加标签

G.add_edge(node1, node2, label=label)

绘图

pos = nx.spring_layout(G)

nx.draw(G, pos)
nx.draw_networkx_edge_labels(G, pos)

得到

我不想要。我不希望标签看起来像 {'label': 'a"} 我希望它只是 a.

可能吗?我看到了一些例子,其中标签被传递到 draw 函数中,这对我不利。我希望将标签存储在图表中并稍后显示。

您可以使用 edge_labels 参数来指定要绘制的内容。示例:

>>> import networkx as nx
>>> G = nx.Graph()
>>> G.add_edge(1, 2, label='a')
>>> pos = nx.spring_layout(G)                                                    
>>> nx.draw(G, pos)                                                              
>>> nx.draw_networkx_edge_labels(G,pos,edge_labels=nx.get_edge_attributes(G,'label'))
{(1, 2): Text(0,0,'a')}