如何在 Networkx 和 matplotlib 中标记多重图的边缘?

Tex*_*xas 5 python label graph networkx

我有一个无向多重图,我想用标签绘制边缘,有什么建议吗?我遵循建议,但仍然没有边缘标签。 通过atomh33ls使用networkx在两个节点之间绘制多条边

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()
Run Code Online (Sandbox Code Playgroud)

无向多重图示例

yat*_*atu 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}
Run Code Online (Sandbox Code Playgroud)

所以这实际上不适用于多重图。您可以遵循与此处相同的想法,使用label权重值对边缘进行操作,并将图形导出到dotwith nx.write_dot,这将labels在可视化中使用这些值。