Python绘制距离成本矩阵有向图
使用Python绘制距离成本矩阵有向图
本文将介绍如何使用Python的matplotlib库,将一个表示距离成本的矩阵绘制成有向图。
1. 导入必要的库
首先,我们需要导入matplotlib.pyplot和numpy库:
import matplotlib.pyplot as plt
import numpy as np
matplotlib.pyplot用于创建和操作图形。numpy用于处理矩阵数据。
2. 定义绘制函数
接下来,我们定义一个名为plot_directed_graph的函数,该函数接收一个距离成本矩阵作为参数,并绘制相应的有向图:
def plot_directed_graph(cost_matrix):
# 创建一个图形对象
fig, ax = plt.subplots()
# 获取矩阵的行数和列数
rows, cols = np.shape(cost_matrix)
# 遍历矩阵中的每个元素
for i in range(rows):
for j in range(cols):
# 如果距离成本大于0,则绘制有向边
if cost_matrix[i][j] > 0:
# 绘制箭头
ax.arrow(i, j, 0.5, 0.5, head_width=0.1, head_length=0.1, fc='black', ec='black')
# 设置坐标轴的范围
ax.set_xlim([-1, rows])
ax.set_ylim([-1, cols])
# 设置坐标轴标签
ax.set_xticks(np.arange(rows))
ax.set_yticks(np.arange(cols))
# 显示图形
plt.show()
函数解释:
fig, ax = plt.subplots(): 创建一个图形对象和一个坐标轴对象。rows, cols = np.shape(cost_matrix): 获取输入矩阵的行数和列数。for i in range(rows):和for j in range(cols):: 嵌套循环遍历矩阵的每个元素。if cost_matrix[i][j] > 0:: 判断距离成本是否大于0,如果大于0,则绘制有向边。ax.arrow(i, j, 0.5, 0.5, head_width=0.1, head_length=0.1, fc='black', ec='black'): 绘制一个箭头,表示从节点i到节点j的有向边。ax.set_xlim([-1, rows])和ax.set_ylim([-1, cols]): 设置坐标轴的范围。ax.set_xticks(np.arange(rows))和ax.set_yticks(np.arange(cols)): 设置坐标轴的刻度。plt.show(): 显示绘制的图形。
3. 调用函数并绘制图形
最后,我们定义距离成本矩阵并调用plot_directed_graph函数绘制图形:
cost_matrix = [
[0, 300, 360, 210, 530, 475, 500, 690],
[300, 0, 380, 270, 230, 285, 200, 390],
[360, 380, 0, 510, 230, 665, 490, 680],
[210, 270, 510, 0, 470, 265, 450, 640],
[530, 230, 230, 470, 0, 515, 260, 450],
[475, 285, 665, 265, 515, 0, 460, 650],
[500, 200, 490, 450, 260, 460, 0, 190],
[690, 390, 680, 640, 450, 650, 190, 0]
]
plot_directed_graph(cost_matrix)
运行代码后,您将看到一个包含8个节点的有向图,图中的箭头表示节点之间的距离成本。
原文地址: https://www.cveoy.top/t/topic/fPRk 著作权归作者所有。请勿转载和采集!