问题描述
我有一个多重图,每对节点有多个边。如何用文本(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()
但是我怎样才能像这样标记边缘?
图片和源代码取自:Drawing multiple edges between two nodes with networkx
解决方法
您可以使用 ax.text
添加文本。您必须使用 x
和 y
参数(使用 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()