How do I draw edge labels for MultiGraph in NetworkX?

Spa*_*ine 8 python matplotlib networkx

In the class networkx.MultiGraph, an edge is keyed by (u, v, key), for instance, ('n1', 'n2', 'key1'). I would like to draw edge labels (say weight, (u, v, key): 10) for MultiGraph by using the function networkx.draw_networkx_edge_labels.

However, edge labels are keyed by a two-tuple (u, v) in draw_networkx_edge_labels, instead of a 3-tuple (u, v, key), as is the case in MultiGraph. This raises ValueError: too many values to unpack.


PS: The parameter edge_labels in draw_networkx_edge_labels is described as follows:

draw_networkx_edge_labels(
    G, pos,
    edge_labels=None, label_pos=0.5,
    font_size=10, font_color='k',
    font_family='sans-serif', font_weight='normal',
    alpha=1.0, bbox=None, ax=None,
    rotate=True, **kwds)
Run Code Online (Sandbox Code Playgroud)

Edge labels in a dictionary of labels keyed by edge two-tuple. Only labels for the keys in the dictionary are drawn.

(Note the "two-tuple" in this description.)

Emi*_*ien 6

我什至找不到如何绘制多图matplotlib(因为不会显示多条边)。但是,如果您导出到dot您将能够看到多个边,并且您可以在边中使用标签属性标记它们。

#!/usr/bin/env python
import networkx as nx

G = nx.MultiGraph()
G.add_node('A')
G.add_node('B')
G.add_edge('A','B', label='foo')
G.add_edge('A','B', label='bar')
# dump dot code
nx.drawing.nx_pydot.write_dot(G, 'multi.dot')
Run Code Online (Sandbox Code Playgroud)

此代码需要networkxpydotGraphViz的

带边标签的多重图

请注意,如果您查看模块networkx.drawing.nx_pylab,该函数的默认行为draw_networkx_edge_labels使用

{(u, v): d for u, v, d in G.edges(data=True)}
Run Code Online (Sandbox Code Playgroud)

作为(默认值)edge_labels属性对于多图会失败,因为字典键必须是唯一的。因此,如果您想使用 绘图matplotlib,您可能需要修改函数draw_networkx_edge_labels