Python 绘制配送路线图代码优化
以下代码使用 Python 的 matplotlib 库绘制配送路线图,并对代码进行优化,修复错误,并提供更易理解的注释:
import matplotlib.pyplot as plt
# 定义坐标点列表
coordinates = [[35, 35], [41, 49], [35, 17], [55, 45], [55, 20], [15, 30], [25, 30], [20, 50], [10, 43], [55, 60], [30, 60]]
# 定义路线,假设这里 Route 是一个包含多个路线的列表,每个路线是一个坐标点的列表
Route = [[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10]], [[0, 2, 1, 3, 4], [5, 7, 6, 8, 9, 10]]] # 例如,这里定义了两个路线
# 循环绘制每条路线
for i in range(len(Route)):
# 遍历每个路线上的坐标点
for j in range(len(Route[i])):
# 在坐标点的首尾添加 0,方便连接路线
Route[i][j].insert(0, 0)
Route[i][j].append(0)
# 绘制路线图
fig, ax = plt.subplots()
ax.set_title('配送路线图')
ax.set_xlabel('X')
ax.set_ylabel('Y')
# 绘制坐标点
for i, coordinate in enumerate(coordinates):
ax.scatter(coordinate[0], coordinate[1], color='b')
ax.annotate(i, (coordinate[0] + 1, coordinate[1]))
# 绘制路线
for route in Route:
for j in range(len(route)):
x = [coordinates[i][0] for i in route[j]]
y = [coordinates[i][1] for i in route[j]]
ax.plot(x, y, marker='o')
plt.show() # 在循环外部显示图表
代码优化说明:
- 导入
matplotlib库:在代码开头添加import matplotlib.pyplot as plt导入matplotlib库,以便使用其绘图功能。 - 定义
Route变量:代码中假设Route是一个包含多个路线的列表,每个路线是一个坐标点的列表。代码中给Route变量赋予了示例数据,您可以根据实际情况修改Route的值。 - 修复
plt.show()的位置:将plt.show()从for循环中移到循环外部,确保只显示一张最终的图表。 - 优化坐标点标注:将坐标点的标注位置稍微偏移,以避免与坐标点重叠。
这段代码使用 matplotlib 库绘制了多个配送路线,每个路线由多个坐标点组成。代码首先定义了每个点的坐标,然后定义了每条路线的顺序,最后通过循环绘制了每条路线。这段代码可以帮助您理解如何使用 Python 绘制配送路线图,并提供了代码优化和错误修复的示例。
原文地址: https://www.cveoy.top/t/topic/orTA 著作权归作者所有。请勿转载和采集!