![](/img/trans.png)
[英]How to label edges of a Multigraph in Networkx and matplotlib?
[英]How to label multiple edges for a fixed pair of nodes in a Multigraph
我有一个多重图,每对节点有多个边。 我怎样才能 label 所有边缘都带有文本(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()
运行上面的代码后,我会得到这里显示的图像。
但是我怎么能像这样 label 边缘?
图片和源代码取自: 使用networkx在两个节点之间绘制多条边
您可以使用ax.text
添加文本。 您必须使用x
和y
参数(使用e[2]
)来停止标签覆盖。
G=nx.MultiGraph ([(1,2,{'label':'A'}),(1,2,{'label':'B'}),(1,2,{'label':'C'}),(3,1,{'label':'D'}),(3,2,{'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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.