如何在Networkx和matplotlib中为多重图的边标注标签?

5

我有一个无向多重图,想要在边上加上标签,您有什么建议?我尝试了以下的建议,但还是没有边上的标签。 在networkx中绘制两个节点之间的多条边 来自 atomh33ls

G=nx.MultiGraph ()
G.add_edge(1,2,weight=7)
G.add_edge(1,2,weight=2)
G.add_edge(1,2,weight=3)
G.add_edge(3,1,weight=2)
G.add_edge(3,2,weight=3)

node_label = nx.get_node_attributes(G,'id')
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, label=node_label)
nx.draw_networkx_labels(G, pos, label=node_label)
edge_labels=nx.get_edge_attributes(G,'weight')
ax = plt.gca()
for e in G.edges:
    ax.annotate("",
                xy=pos[e[0]], xycoords='data',
                xytext=pos[e[1]], textcoords='data',
                arrowprops=dict(arrowstyle="-", color="0.5",
                                shrinkA=5, shrinkB=5,
                                patchA=None, patchB=None,
                                connectionstyle="arc3,rad=rrr".replace('rrr',str(0.3*e[2])
                                ),
                                ),
                )
#nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.axis('off')
plt.show()

无向多重图示例

2个回答

4
nx.get_edge_attributes 返回的字典结构为 (source, dest, enum):attr,其中第三个字段只是枚举每条边的出现次序。由于字典中的键必须唯一,因此第三个字段是必要的。但这将意味着它不能在 nx.draw_networkx_edge_labels 中使用,因为它需要一个结构化的 (source, dest):attr 字典。
nx.get_edge_attributes(G,'weight')
# {(1, 2, 0): 7, (1, 2, 1): 2, (1, 2, 2): 3, (1, 3, 0): 2, (2, 3, 0): 3}

因此,这不能在MultiGraphs上工作。您可以按照此处的相同思路执行以下操作:使用label将边缘标记为权重值,并使用nx.write_dot将图导出到dot中,该方法将在可视化中使用这些labels


4

感谢 @yatu。这是目前为止关于无向多重图标记的优雅解决方案。请给我更多建议来改善风格!

import networkx as nx
import matplotlib.pyplot as plt
from IPython.display import Image

G=nx.MultiGraph ()
G.add_edge(1,2,weight=1)
G.add_edge(1,2,weight=2)
G.add_edge(1,2,weight=3)
G.add_edge(3,1,weight=4)
G.add_edge(3,2,weight=5)
for edge in G.edges(data=True): edge[2]['label'] = edge[2]['weight']
node_label = nx.get_node_attributes(G,'id')
pos = nx.spring_layout(G)
node_label = nx.get_node_attributes(G,'id')
pos = nx.spring_layout(G)
p=nx.drawing.nx_pydot.to_pydot(G)
p.write_png('multi.png')
Image(filename='multi.png')

Solution


我会在有时间的时候再仔细看一遍。 - yatu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接