如何绘制含字符串/整数类型节点ID的多路线图?解决索引错误
解决NumPy索引类型错误:绘制VRP路线图的问题
给定以下数据:
all_Ids = ["01", "02", 1, 2, 3, 4, 5] all_xs = [12, 50, 36, 81, 70, 66, 34] all_ys = [41, 50, 97, 22, 11, 89, 33] Routes = [["01", 2, 3, "01"], ["02", 1, "02"], ["01", 4, "01"], ["02", 5, "02"]]
其中all_Ids包含字符串和整数类型的节点ID,all_xs/all_ys是对应节点的坐标;Routes是闭合路线列表。编写的绘图函数SolutionPlot在调用时触发错误:
IndexError: arrays used as indices must be of integer (or boolean) type
原函数代码:
def SolutionPlot(xx, yy, all_ids, RoutesContainer): fig, ax = plt.subplots() fig.set_size_inches(6, 6) allxs = np.array(xx) allys = np.array(yy) for v in RoutesContainer: final_route = v final_route = np.array(final_route) ax.plot(allxs[final_route], allys[final_route], ls="-", marker="o", markersize=8) plt.xlim([0, 100]) plt.ylim([0, 100]) plt.title("Vehicle Routing Problem (Clarke & Wright Heuristic)") for xi, yi, pidi in zip(xx, yy, all_ids): ax.annotate(str(pidi), xy=(xi,yi), fontsize = 13) fig = plt.gcf() fig.set_size_inches(8, 8) plt.style.use('seaborn-dark-palette') plt.show()
错误原因
allxs和allys是NumPy数组,而final_route中混合了字符串(如"01")和整数ID。NumPy数组要求索引必须是整数或布尔类型,用字符串直接索引会触发IndexError。同时调用函数时存在参数笔误:原变量是all_xs、all_ys、all_Ids,但调用时写的是allxs、allys、allIds,需要修正。
解决方案
先建立ID到数组索引的映射字典,将路线中的每个ID转换为对应的坐标列表索引,再用索引获取坐标绘图。修改后的函数如下:
import numpy as np import matplotlib.pyplot as plt def SolutionPlot(xx, yy, all_ids, RoutesContainer): # 建立ID到索引的映射:同时处理字符串和整数类型的ID id_to_index = {} for idx, id_val in enumerate(all_ids): # 为字符串ID和整数ID分别建立映射 id_to_index[id_val] = idx id_to_index[str(id_val)] = idx fig, ax = plt.subplots() fig.set_size_inches(6, 6) allxs = np.array(xx) allys = np.array(yy) for v in RoutesContainer: # 将路线中的每个ID转换为对应的索引 route_indices = [id_to_index[id_val] for id_val in v] route_indices = np.array(route_indices) ax.plot(allxs[route_indices], allys[route_indices], ls="-", marker="o", markersize=8) plt.xlim([0, 100]) plt.ylim([0, 100]) plt.title("Vehicle Routing Problem (Clarke & Wright Heuristic)") for xi, yi, pidi in zip(xx, yy, all_ids): ax.annotate(str(pidi), xy=(xi,yi), fontsize = 13) fig = plt.gcf() fig.set_size_inches(8, 8) plt.style.use('seaborn-dark-palette') plt.show() # 修正参数名后调用函数 SolutionPlot(all_xs, all_ys, all_Ids, Routes)
关键修改点
- 创建
id_to_index字典,为每个ID(无论字符串还是整数类型)建立到坐标索引的映射,确保路线中的ID能正确转换为数组索引。 - 遍历路线时,将每个ID转换为对应的索引,再用索引访问NumPy数组获取坐标。
- 修正调用函数时的参数名错误,与原始变量名保持一致。
内容的提问来源于stack exchange,提问作者Yannis_Tr
相关产品推荐
相关产品推荐

