How do I draw edge labels for MultiGraph in NetworkX?

痞子三分冷 提交于 2020-06-25 18:10:19

问题


In 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 draw_networkx_edge_labels.

However, edge labels are keyed by a two-tuple (u, v) in draw_networkx_edge_labels, instead of 3-tuple (u,v,key) in MultiGraph, causing 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)

Edge labels in a dictionary keyed by edge two-tuple of text labels (default=None). Only labels for the keys in the dictionary are drawn.


回答1:


I could not even find how to draw a multigraph with matplotlib (because the multiple edges won't show up). However if you export to dot you will be able to see multiple edges, and you can label them with a label attribute in the edges.

#!/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')

nx.write_dot(G,'multi.dot')

Note that if you look into nx_pylab.py, the default behavior of draw_networkx_edge_labels is to use dict(((u, v), d) for u, v, d in G.edges(data=True)) as the edge_labels attribute which will fail for multigraphs because the dictionnary key has to be unique. Thus, if you want to plot using matplotlib, you will probably need to modify the draw_networkx_edge_labels method.



来源:https://stackoverflow.com/questions/32905262/how-do-i-draw-edge-labels-for-multigraph-in-networkx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!