使用networkx在两个节点之间绘制多条边

2022-01-25 00:00:00 python networkx graph label edges

问题描述

我需要在两个节点之间绘制一个有多个边(具有不同权重)的有向图.也就是说,我有节点 A 和 B 以及长度为 2 的边 (A,B) 和长度为 3 的边 (B,A).

I need to draw a directed graph with more than one edge (with different weights) between two nodes. That is, I have nodes A and B and edges (A,B) with length=2 and (B,A) with length=3.

我已经尝试过使用 G=nx.Digraph 和 G=nx.Multidigraph.当我绘制它时,我只能看到一个边缘和一个标签.有什么办法吗?

I have tried both using G=nx.Digraph and G=nx.Multidigraph. When I draw it, I only get to view one edge and only one of the labels. Is there any way to do it?


解决方案

对上面回复的改进是添加 connectionstyle 到 nx.draw,这样可以在图中看到两条平行线:

An improvement to the reply above is adding the connectionstyle to nx.draw, this allows to see two parallel lines in the plot:

import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph() #or G = nx.MultiDiGraph()
G.add_node('A')
G.add_node('B')
G.add_edge('A', 'B', length = 2)
G.add_edge('B', 'A', length = 3)

pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, connectionstyle='arc3, rad = 0.1')
edge_labels=dict([((u,v,),d['length'])
             for u,v,d in G.edges(data=True)])

plt.show()

相关文章