如何为多重图中的一对固定节点标记多条边

问题描述

我有一个多重图,每对节点有多个边。如何用文本(1,2,3,4,5)标记所有边缘?

pos = nx.random_layout(G)
nx.draw_networkx_nodes(G,pos,node_color = 'r',node_size = 100,alpha = 1)
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])
                                ),),)
plt.axis('off')
plt.show()              

运行上面的代码后,我会得到这里显示的图像。

enter image description here

但是我怎样才能像这样标记边缘?

enter image description here

图片和源代码取自:Drawing multiple edges between two nodes with networkx

解决方法

您可以使用 ax.text 添加文本。您必须使用 xy 参数(使用 e[2])来停止标签叠加。

G=nx.MultiGraph ([(1,2,{'label':'A'}),(1,{'label':'B'}),{'label':'C'}),(3,1,{'label':'D'}),{'label':'E'})])
pos = nx.random_layout(G)
nx.draw_networkx_nodes(G,pos,node_color = 'r',node_size = 100,alpha = 1)
ax = plt.gca()
for e in G.edges(keys=True,data=True):
    print(e)
    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])
                                ),),)
    ax.text((pos[e[0]][0]+pos[e[1]][0])*0.5,(pos[e[0]][1]+pos[e[1]][1])*0.5,str(e[3]['label']))
plt.axis('off')
plt.show()