- 导入networkx库和matplotlib库
import networkx as nx
import matplotlib.pyplot as plt
- 创建带权重的图
G = nx.Graph()
G.add_edge('A', 'B', weight=0.6)
G.add_edge('A', 'C', weight=0.2)
G.add_edge('C', 'D', weight=0.1)
G.add_edge('C', 'E', weight=0.7)
G.add_edge('E', 'F', weight=0.9)
- 创建节点的位置
pos = nx.spring_layout(G)
- 获取边的权重
edge_labels=dict([((u,v,),d['weight']) for u,v,d in G.edges(data=True)])
- 绘制节点和边
nx.draw_networkx_nodes(G, pos, node_size=700)
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
- 显示图像
plt.axis('off')
plt.show()