在networkx(Matplotlib)中按权重着色边缘
要在 networkx 中按权重对边缘进行着色,可以执行以下步骤−
- 设置图形大小并调整子图之间和周围的填充。
- 使用边缘,名称或图形属性初始化图形。
- 将节点添加到当前图形。
- 将边缘添加到当前图形节点。
- 迭代给定图的边缘并为其设置一些权重。
- 使用 权重 绘制当前图形以用于边缘颜色。
- 要显示图形,请使用 show() 方法。
示例
import random as rd
import matplotlib.pylab as plt
import networkx as nx
plt.rcParams [“figure.figsize”] = [7.50,3.50]
plt.rcParams [“figure.autolayout”] = True
G = nx.DiGraph()
G.add_nodes_from([1,2,3,4])
G.add_edges_from([(1,2),(2,3),(3,4),(4,1),(1,3)])
for u,v,d in G.edges(data = True):
d ['weight'] = rd.random()
edges,weights = zip(* nx.get_edge_attributes(G,'weight').items())
nx.draw(G,node_color ='b',edge_color = weights,width = 2,with_labels = True)
plt.show()