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

Cartopy经纬度轴格式化失效:如何让纬度显示一位小数?

Cartopy经纬度标签格式化不生效的解决方法

你尝试用Cartopy绘制地图,想要将纬度标签格式化为带一位小数的形式(如7.0°S),但直接设置LongitudeFormatter和LatitudeFormatter后并未生效,纬度仍显示为7°S。问题出在网格线的标签生成逻辑上,以下是具体原因和解决办法:

问题根源

当调用ax.gridlines(draw_labels=True)时,Cartopy是通过网格线对象(Gridlines)自身来生成和格式化标签的,而非使用matplotlib轴(ax.xaxis/ax.yaxis)的格式化器。因此直接设置轴的formatter不会作用到网格线标签上。

解决代码

修改代码,通过网格线对象直接配置格式化器:

import matplotlib.pyplot as plt
import cartopy.mpl.ticker, cartopy.crs as ccrs

# 定义投影
ProjIn   = ccrs.PlateCarree(central_longitude=0) 
ProjPlot = ccrs.PlateCarree(central_longitude=0) 

# 创建画布和轴
fig, ax = plt.subplots(figsize=(15,6), subplot_kw={'projection':ProjPlot})
ax.set_extent((-60, 10, -10, 10), crs=ProjIn)

# 创建网格线对象并启用标签
gl = ax.gridlines(crs=ProjIn)
gl.draw_labels = True

# 为网格线设置经纬度格式化规则
gl.xformatter = cartopy.mpl.ticker.LongitudeFormatter(dms=False, number_format='03.1f')
gl.yformatter = cartopy.mpl.ticker.LatitudeFormatter(dms=False, number_format='03.1f')

# 添加海岸线
ax.coastlines()
plt.show()

关键说明

  • 先创建Gridlines对象,再通过gl.draw_labels = True启用标签绘制
  • 使用gl.xformatter和gl.yformatter指定格式化器,这样设置的number_format='03.1f'就会生效,生成带一位小数的经纬度标签

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:12:37