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

使用Cartopy绘制气旋轨迹时跨180°经线连线异常的解决方法

解决Cartopy绘制跨180度经线气旋轨迹的断线问题

问题描述

使用Cartopy绘制气旋的(纬度,经度)轨迹时,跨越180度经线的点会被直接连接,形成横贯地球的长线。已尝试按日期排序数据,但问题仍未解决。

解决方案

这是经度不连续性导致的问题:当轨迹从接近180°的位置跳转到接近-180°的位置时,matplotlib会默认连接两点,忽略球面地理逻辑。解决关键是在经度跳变超过180°的相邻点间插入NaN,让绘图时自动中断线条。

具体实现步骤

  1. 对单个气旋的轨迹数据,提取经纬度数组并计算相邻经度的差值
  2. 定位差值绝对值大于180°的位置,在这些位置的下一个索引处插入NaN(纬度数组同步插入)
  3. 使用处理后的经纬度数据绘图

修改后的代码示例

import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

colormap = "RdYlBu_r"

pole_lon = -180
pole_lat = 90

fig = plt.figure(figsize=(20, 20))

ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_global()

ax.add_feature(cartopy.feature.OCEAN, color='white', zorder=0)
ax.add_feature(cartopy.feature.LAND, color='lightgray', zorder=0,
               linewidth=0.5, edgecolor='black')

ax.gridlines(draw_labels=True, linewidth=0.5, color='gray',
             xlocs=range(-180, 180, 15), ylocs=range(-90, 90, 15))

ax.coastlines(resolution='50m', linewidth=0.3, color='black')
ax.set_title('', fontsize=10, fontweight='bold')

crs = ccrs.RotatedPole(pole_longitude=pole_lon, pole_latitude=pole_lat)
ax.set_extent([-180, 180, -90, 90], crs=ccrs.PlateCarree())

g = df.groupby('label')['xlat', 'xlon', 'date']

for i in range(len(c_l)):
    g_tmp = g.get_group(c_l[i]).sort_values(by='date', ascending=True)
    lats = g_tmp['xlat'].values
    lons = g_tmp['xlon'].values
    
    # 计算相邻经度差,定位跳变点
    lon_diff = np.diff(lons)
    jump_indices = np.where(np.abs(lon_diff) > 180)[0]
    
    # 插入NaN中断线条
    if jump_indices.size > 0:
        insert_pos = jump_indices + 1
        lats = np.insert(lats, insert_pos, np.nan)
        lons = np.insert(lons, insert_pos, np.nan)
    
    ax.plot(lons, lats, '-', transform=crs)

补充说明

  • 若你的RotatedPole投影使用的是[0, 360]范围的经度,判断逻辑不变,仍以差值绝对值>180°为跳变标准
  • np.insert会在指定位置插入NaN,matplotlib遇到NaN时会自动中断当前线条,后续点重新开始绘制,避免跨球连线

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:52:53