You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将networkx绘制的VRP路径图叠加到mplleaflet地图报错如何解决

你当前已经生成的静态VRP路径图如下:
networkx路径图

报错原因

你遇到的ValueError: Unrecognized code: S错误是因为长期未更新的mplleaflet仅支持matplotlib的基础路径命令,networkx默认绘制逻辑生成的路径中包含了其不支持的二次贝塞尔曲线命令码S,因此解析失败。

正确实现方案

需要调整networkx的绘制逻辑,规避mplleaflet不兼容的样式特性,统一使用简单的点、线绘制逻辑,修改后的实现代码如下:

import networkx as nx
import matplotlib.pyplot as plt
import mplleaflet

# 你原有定义的new_vlist、PickupColor、DataProblem类保持不变

def DrawNetworkOnMap():
    G = nx.DiGraph()
    locations = DataProblem()._locations
    edge_color_list = []
    node_color_map = {}
    color_idx = 0

    # 统一构建图的节点、边及样式映射
    for route in new_vlist:
        current_color = PickupColor(color_idx)
        point_count = len(route)
        for i in range(point_count):
            node_id = route[i]
            if node_id not in node_color_map:
                node_color_map[node_id] = current_color
            G.add_node(node_id, pos=(locations[node_id][0], locations[node_id][1]))
            if i > 0:
                G.add_edge(route[i-1], route[i])
                edge_color_list.append(current_color)
        color_idx += 1
    
    # 起点0设置为黑色
    node_color_map[0] = 'k'
    node_color_list = [node_color_map[node] for node in G.nodes()]
    pos = nx.get_node_attributes(G, 'pos')

    # 分开绘制边和节点,避免nx.draw默认逻辑生成不兼容路径
    # 边可以先试默认实线,确认没问题再保留dashed样式
    nx.draw_networkx_edges(G, pos, edgelist=G.edges(), edge_color=edge_color_list, width=2, style='dashed')
    # 用最简单的圆形节点,避免复杂形状触发不兼容问题
    nx.draw_networkx_nodes(G, pos, node_color=node_color_list, node_size=100, node_shape='o')
    # 需要节点标签可以取消注释下面一行
    # nx.draw_networkx_labels(G, pos, font_size=10, font_color='w')

    plt.axis('off')
    # 二选一:直接在浏览器打开叠加后的地图
    mplleaflet.show()
    # 或者保存为本地HTML文件
    # mplleaflet.save_html('vrp_route_map.html')

注意事项

  • 请确认你的locations数组中每个点位的坐标顺序为(经度, 纬度),如果原始存储顺序是(纬度, 经度),需要调换两个值的位置,否则点位会偏移到错误区域。
  • 若修改后仍报错,可先注释掉边的style='dashed'参数使用默认实线测试,部分旧版本mplleaflet对虚线样式的路径解析存在兼容问题。
  • 尽量减少复杂自定义样式的使用,mplleaflet对matplotlib的新特性支持度极低,基础的圆形节点、实/虚线边是兼容性最高的选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 16:06:02