如何在SouthPolarStereo投影下实现跨±180°经度的平滑轨迹
解决Cartopy极地轨迹跨±180°经线的异常线条问题
使用Cartopy绘制极地附近轨迹时,若轨迹点穿过±180°经线,plot方法会绘制出绕地球一圈的异常长线(如示例代码所示)。仅显示标记时无此问题,核心原因是PlateCarree坐标系中,170°到-170°的经度差被计算为340°,而非实际需要的20°短路径。
方案1:手动调整经度数据
将跨180°的负经度转换为大于180°的正数(或正经度转负),让经度序列保持连续。修改示例代码如下:
import matplotlib.pyplot as plt import cartopy.crs as ccrs fig = plt.figure(figsize=[8, 8]) ax = fig.add_subplot(111, projection=ccrs.SouthPolarStereo()) ax.set_extent([-180, 180, -90, -60], ccrs.PlateCarree()) ax.gridlines(crs=ccrs.PlateCarree()) ax.coastlines() # 将-170°转换为190°,使经度序列连续 ax.plot([135, 170, 190], [-71, -75, -75], marker='*', transform=ccrs.PlateCarree()) plt.show()
方案2:自动调整经度函数(适用于多点轨迹)
如果轨迹包含大量点,可编写函数自动调整经度,确保相邻点的经度差始终小于180°:
import matplotlib.pyplot as plt import cartopy.crs as ccrs def adjust_lon(lon_list): adjusted = [] prev_lon = lon_list[0] adjusted.append(prev_lon) for lon in lon_list[1:]: diff = lon - prev_lon if diff > 180: lon -= 360 elif diff < -180: lon += 360 adjusted.append(lon) prev_lon = lon return adjusted fig = plt.figure(figsize=[8, 8]) ax = fig.add_subplot(111, projection=ccrs.SouthPolarStereo()) ax.set_extent([-180, 180, -90, -60], ccrs.PlateCarree()) ax.gridlines(crs=ccrs.PlateCarree()) ax.coastlines() # 自动调整经度 original_lons = [135, 170, -170] adjusted_lons = adjust_lon(original_lons) ax.plot(adjusted_lons, [-71, -75, -75], marker='*', transform=ccrs.PlateCarree()) plt.show()
效果说明
上述两种方法都能让线条沿着极地的短路径连接,避免出现绕地球的异常长线,同时保留标记和线条的正常显示。
内容的提问来源于stack exchange,提问作者Keita Mizukoshi
相关产品推荐
相关产品推荐

