在我的 directed networkx graph 中,我根据权重绘制了边缘颜色。我可以将它们作为标签添加到我的图表中,但它出现了两次。我如何只添加一次不同颜色的边缘标签和方向
`elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.10]
emed=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.05 and d['weight'] <0.10]
esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <0.05]
# red_patch = mpatches.Patch(color='red', label= "Probablity < 0.05")
# plt.legend(handles=[red_patch])
# blue_patch = mpatches.Patch(color='blue', label='Probablity > 0.10')
# plt.legend(handles=[blue_patch])
# green_patch = mpatches.Patch(color='green',label='Probablity > 0.15 and Probablity < 0.10')
# plt.legend(handles=[green_patch])
pos=nx.spring_layout(G) # positions for all nodes
edge_labels = nx.get_edge_attributes(G,'weight')
# nodes
nx.draw_networkx_nodes(G,pos,node_size=4000,node_color= "grey")
# edges
nx.draw_networkx_edges(G,pos,edgelist=elarge,
width=2,alpha = 0.6,edge_color = "b",label = "Probablity > 0.10",arrows=True)
nx.draw_networkx_edges(G,pos,edgelist=esmall,
width=3,alpha=0.6,edge_color='r',label = "Probablity < 0.05",arrows=True)
nx.draw_networkx_edges(G,pos,edgelist=emed,
width=3,alpha=0.6,edge_color='g',label = "'Probablity > 0.15 and Probablity < 0.10'",arrows=True)
# labels
nx.draw_networkx_edge_labels(G, pos, labels = edge_labels,arrows=False)
nx.draw_networkx_labels(G,pos,labels1,font_size=12,font_family='sans-serif')
plt.legend(numpoints = 1)
plt.axis('on')
plt.show()
请您参考如下方法:
对我来说,这看起来像是 networkx 中的一个错误(在 1.11 中仍然存在)。看着 source code对于 draw_networkx_edges,它创建边,然后创建箭头作为较粗的线。
创建边后,有命令edge_collection.set_label(label),它设置边的标签。但是在创建箭头之后它也有 arrow_collection.set_label(label)。因此,边缘和箭头最终都在图例中标记(这就是为什么您会在图例中看到标签以两个相关联的宽度出现)。
我相信在您的计算机上转到 networkx 代码并简单地注释掉 arrow_collection.set_label(label) 就足够了。另一种方法是绘制不带箭头的边并给它一个标签,然后用箭头但不带标签重新绘制它(使用相同的颜色)。
我已经提交了 bug report在这一点上,因为我想不出任何人为什么想要一个单独的箭头标签。
