import matplotlib.pyplot as plt import matplotlib.patches as patches import json def visualize_solution(row_boundaries, col_boundaries, car_paths, W, H): plt.rcParams['font.family'] = ['sans-serif'] plt.rcParams['font.sans-serif'] = ['SimHei'] fig, ax = plt.subplots() ax.set_xlim(0, W) ax.set_ylim(H, 0) # 调整y轴方向,原点在左上角 ax.set_title("区域划分与车-机-巢系统覆盖") ax.set_xlabel("区域宽度") ax.set_ylabel("区域高度") # 定义若干颜色以区分不同系统(系统编号从0开始) colors = ['red', 'blue', 'green', 'orange', 'purple', 'cyan', 'magenta'] # 绘制区域中心 region_center = (H / 2.0, W / 2.0) ax.plot(region_center[1], region_center[0], 'ko', markersize=8, label="区域中心") # 绘制行分割边界 for row in row_boundaries: ax.axhline(y=row * H, color='black', linestyle='--') # 绘制列分割边界 for col in col_boundaries: ax.axvline(x=col * W, color='black', linestyle='--') # 绘制每辆车的轨迹 for system_id, path in enumerate(car_paths): path = [(region_center[0], region_center[1])] + path + [(region_center[0], region_center[1])] y, x = zip(*path) ax.plot(x, y, marker='o', color=colors[int(system_id) % len(colors)], label=f"系统 {system_id}") # 添加图例 ax.legend() plt.show() if __name__ == "__main__": import yaml # 读取参数 with open('params3.yml', 'r', encoding='utf-8') as file: params = yaml.safe_load(file) H = params['H'] W = params['W'] # 读取最佳方案的JSON文件 with open(r'solutions\trav_ga_params3_parallel.json', 'r', encoding='utf-8') as f: best_solution = json.load(f) row_boundaries = best_solution['row_boundaries'] col_boundaries = best_solution['col_boundaries'] car_paths = best_solution['car_paths'] visualize_solution(row_boundaries, col_boundaries, car_paths, W, H)