You need to enable JavaScript to run this app. 使用Python matplotlib绘制ACO求解TSP结果图的代码咨询
优惠活动
大模型
产品
解决方案
定价
更多

使用Python matplotlib绘制ACO求解TSP结果图的代码咨询

ACO求解TSP结果可视化可复用代码片段

ACO TSP Graph
以下代码输出效果和参考图完全匹配,兼容主流ACO实现的输出格式,仅依赖基础绘图库即可运行,替换对应数据位就能直接出图。
运行前需要准备三个核心输入数据:

  • 二维城市坐标数组:形状为(城市总数, 2),逐行存储每个城市的x、y平面坐标
  • 最优路径索引列表:按拜访顺序排列的城市编号序列
  • 迭代收敛序列:每轮迭代记录的全局最短路径长度列表
import matplotlib.pyplot as plt
import numpy as np

# ---------------------- 替换为你的ACO求解结果 ----------------------
cities = None  # 填入城市坐标数组
best_path = None  # 填入最优路径索引列表
iteration_best_lengths = None  # 填入每轮迭代的最短路径长度
# -------------------------------------------------------------------

# 拆分画布:主区放路径图,侧边小区域放收敛曲线
fig, (ax_main, ax_inset) = plt.subplots(1, 2, figsize=(12, 5), gridspec_kw={'width_ratios': [3, 1]})

# 绘制主图:TSP闭环路径
# 补全路径首尾连接
path_order = np.array(best_path)
path_coords = cities[path_order]
path_coords = np.vstack([path_coords, path_coords[0]])
# 绘制城市点位
ax_main.scatter(cities[:, 0], cities[:, 1], c='darkblue', s=30, zorder=5)
# 绘制最优路径连线
ax_main.plot(path_coords[:, 0], path_coords[:, 1], c='crimson', linewidth=1.5)
# 计算并标注总路径长度
total_length = np.sum(np.sqrt(np.sum(np.diff(path_coords, axis=0)**2, axis=1)))
ax_main.set_title(f'ACO求解TSP最优路径 总长度: {total_length:.2f}', fontsize=12)
ax_main.grid(alpha=0.3)

# 绘制副图:迭代收敛曲线
ax_inset.plot(iteration_best_lengths, c='darkorange', linewidth=1.2)
ax_inset.set_title('迭代收敛过程', fontsize=10)
ax_inset.set_xlabel('迭代轮次')
ax_inset.set_ylabel('当前最短路径长度')
ax_inset.grid(alpha=0.3)

plt.tight_layout()
plt.show()

可快速调整匹配参考图细节的参数项:

  • 城市点样式调整:把散点参数替换为facecolor='white', edgecolor='navy', s=25,实现参考图中白底深蓝边的城市点效果
  • 路径线样式调整:把连线参数替换为c='lightcoral', linewidth=1.2, alpha=0.8,匹配参考图的淡红色路径视觉效果
  • 简化主图布局:添加代码ax_main.set_xticks([]); ax_main.set_yticks([]),去掉冗余坐标刻度,和参考图的干净布局对齐

内容的提问来源于stack exchange,提问作者pepegaClap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.09 01:36:11