如何在NetworkX中绘制MultiGraph的边缘标签? [英] How do I draw edge labels for MultiGraph in NetworkX?

查看:69
本文介绍了如何在NetworkX中绘制MultiGraph的边缘标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,如果您查看模块 ,该功能的默认行为draw_networkx_edge_labels <代码> {{u,v):d表示G.edges中的u,v,d(data = True)}

作为( edge_labels 属性的(默认值))对于多重图形将失败,因为字典键必须是唯一的.因此,如果要使用 matplotlib 进行绘图,则可能需要修改函数 draw_networkx_edge_labels .

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)

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.)

解决方案

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')
# dump dot code
nx.drawing.nx_pydot.write_dot(G, 'multi.dot')

This code requires networkx, pydot, and GraphViz.

Note that if you look into the module networkx.drawing.nx_pylab, the default behavior of the function draw_networkx_edge_labels is to use

{(u, v): d for u, v, d in G.edges(data=True)}

as the (default value for 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 function draw_networkx_edge_labels.

这篇关于如何在NetworkX中绘制MultiGraph的边缘标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆