如何在Cartopy正射投影中设置0-360°经度网格标签?
解决Cartopy正射投影下0-360°经度标签的问题
要在Cartopy正射投影中实现0-360°格式的经度标签,核心方案是自定义经度格式化函数,替换默认的LongitudeFormatter。因为正射投影属于非矩形投影,官方格式化器无法直接输出0-360范围的数值,自定义函数可以直接处理经度值,将负数转换为0-360的正数格式。
具体实现步骤
- 编写自定义格式化函数:通过取模运算将任意经度值转换为0-360°范围
- 用自定义函数替换
gl.xformatter的默认设置
修改后的完整代码
import matplotlib.pyplot as plt import cartopy.crs as ccrs from cartopy.mpl.ticker import (LatitudeFormatter, LongitudeLocator, LatitudeLocator) # 自定义经度格式化函数,将经度转为0-360°格式 def lon_formatter(x, pos): lon = x % 360 return f'{lon:.0f}°' plotproj = ccrs.Orthographic(central_longitude=90, central_latitude=45) mgeodetic = ccrs.Geodetic() fig1, ax1 = plt.subplots(1, 1, figsize=(10.0, 10.0), constrained_layout=True, subplot_kw={"projection": plotproj}) ax1.set_global() # 网格线设置 longlocs = [0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360] gl = ax1.gridlines(draw_labels=True, x_inline=True, xpadding=0, ypadding=0, xlocs=longlocs) gl.top_labels = False gl.left_labels = False gl.xlocator = LongitudeLocator(nbins=12) gl.ylocator = LatitudeLocator(nbins=12) # 使用自定义格式化器替代默认的LongitudeFormatter gl.xformatter = lon_formatter gl.yformatter = LatitudeFormatter(auto_hide=False) ax1.invert_xaxis() # 保留你需要的经度方向 plt.show()
说明
自定义函数lon_formatter通过x % 360处理所有经度值:
- 原本的负数经度(如-150°)会被转换为210°
- 正数经度保持不变,360°会被转换为0°(符合地理规范)
- 该方法不受投影类型限制,适用于正射投影这类非矩形投影
内容的提问来源于stack exchange,提问作者Riley D.
相关产品推荐
相关产品推荐

