给两个edge_arr,用nx画出图的结构,可以标出重点线路
import matplotlib.pyplot as plt # 导入 Matplotlib 工具包
import networkx as nx # 导入 NetworkX 工具包
# 问题 2:无向图的最短路问题(司守奎,数学建模算法与应用,P43,例4.3)
import numpy as np
def draw_graph(edge_arr):
G2 = nx.DiGraph() # 创建:空的 有向图
for i in range(0,edge_arr.shape[0]):
G2.add_edge(edge_arr[i][0], edge_arr[i][1], weight=1) # 添加 带权边,weight表示边权
# 两个指定顶点之间的最短加权路径
# minWPath_v1_v5 = nx.dijkstra_path(G2, source=1, target=5) # 顶点 0 到 顶点 3 的最短加权路径
# print("顶点 v1 到 顶点 v5 的最短加权路径: ", minWPath_v1_v5)
# 两个指定顶点之间的最短加权路径的长度
# lMinWPath_v1_v5 = nx.dijkstra_path_length(G2, source=1, target=5) # 最短加权路径长度
# print("顶点 v1 到 顶点 v5 的最短加权路径长度: ", lMinWPath_v1_v5)
pos = nx.spring_layout(G2) # 用 FR算法排列节点
nx.draw(G2, pos, with_labels=True, alpha=0.5)
labels = nx.get_edge_attributes(G2, 'weight')
nx.draw_networkx_edge_labels(G2, pos, edge_labels=labels)
plt.show()
# plt.show()
# edgeList = []
# for i in range(len(minWPath_v1_v5) - 1):
# edgeList.append((minWPath_v1_v5[i], minWPath_v1_v5[i + 1]))
# nx.draw_networkx_edges(G2, pos, edgelist=edgeList, edge_color='m', width=4) # 设置边的颜色
arr1=np.array([[0, 2], [0, 3], [1, 2], [2, 4], [4, 0], [4, 1], [2, 3]])
arr2=np.array([[0, 1], [4, 0], [4, 3], [2, 4], [2, 3]])
draw_graph(arr1)
draw_graph(arr2)
# plt.axis("off")
# YouCans, XUPT
参考文献
python 使用networkx绘制带权无向图和带权有向图,以及标注特定路径
https://blog.csdn.net/qq_45956730/article/details/127352658
networkx绘制拓扑图节点的边和权
https://blog.csdn.net/zhangphil/article/details/121105598
NetworkX画图:nx.draw_networkx(函数详解)
https://blog.csdn.net/Ducky_/article/details/125173457
利用NetworkX画网络图
https://zhuanlan.zhihu.com/p/33011750