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

使用Cartopy绘制跨国际日期变更线的GeoJSON航线避免异常连线

跨国际日期变更线航线异常连线修复方案

问题原因

使用GeoPandas直接绘制跨180°经线的航线时,绘图逻辑会直接按照坐标数值的线性距离连线,经度为179°和-179°的两个点会被从地图西侧连接到东侧,产生横跨全球的异常线段。

解决方案

修改代码逻辑,使用Cartopy内置的几何绘制接口替代GeoPandas的默认plot方法,自动处理跨投影边界的几何分割,同时调整图层绘制顺序避免航线被背景遮挡。

完整修改后代码

import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import geopandas as gpd

def main():
    # 读取本地航线数据
    tracks = gpd.read_file('tracks.json')

    # 初始化画布和投影轴,保持4000x2000输出分辨率不变
    fig = plt.figure(dpi=100, figsize=(40, 20), frameon=False)
    ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
    ax.set_extent([-180, 180, -90, 90], ccrs.PlateCarree())
    ax.set_axis_off()

    # 先绘制背景底图
    img = plt.imread('c:/scripts/NASA_BM_default.jpg')
    img_extent = (-180, 180, -90, 90)
    ax.imshow(img, origin='upper', extent=img_extent, transform=ccrs.PlateCarree(), aspect='auto')

    # 使用Cartopy接口绘制航线,自动处理跨日期变更线的几何分割
    ax.add_geometries(
        tracks.geometry,
        crs=ccrs.PlateCarree(),
        facecolor='none',
        edgecolor='yellow',
        linewidth=1
    )

    # 调整画布边距实现无边界输出
    fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
    plt.show()
    plt.close(fig)

if __name__ == "__main__":
    main()

关键修改说明

  • 移除了冗余的重复轴设置代码,避免逻辑冲突
  • 调整图层绘制顺序,先画背景再画航线,避免航线被底图遮挡
  • 用Cartopy的add_geometries替代GeoPandas默认的plot方法绘制航线,会自动对跨180°经线的航线做分割处理,不会产生横跨全图的异常连线
  • 完全保留原有输出分辨率、无边界效果的要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:57:02