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

Cartopy高纬度非矩形投影下右侧纬度标签隐藏失效问题

Cartopy中right_labels=False无法隐藏右侧纬度标签的解决方法

问题描述

使用Cartopy绘制阿拉斯加区域地图时,设置gridlines.right_labels = False无法隐藏右侧的纬度标签,但top_labels=False和bottom_labels=False可以正常隐藏对应位置的标签。该问题出现在使用ax.set_boundary()自定义地图边界的场景下,当前使用Cartopy版本为0.21.1。

复现代码

import numpy as np
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import matplotlib.ticker as mticker
import matplotlib.path as mpath
import cartopy.feature as cf

"""
Plot Alaska
"""

# Map View Using Cartopy
fig = plt.figure(figsize=(8,6))

xmin=-163
xmax=-120
ymin=50
ymax=71

proj = ccrs.LambertConformal(central_longitude=(xmin+xmax)/2, central_latitude=(ymin+ymax)/2)
ax = fig.add_subplot(1, 1, 1, projection=proj)
n = 20
aoi = mpath.Path(
    list(zip(np.linspace(xmin, xmax, n), np.full(n, ymax))) + \
    list(zip(np.full(n, xmax), np.linspace(ymax, ymin, n))) + \
    list(zip(np.linspace(xmax, xmin, n), np.full(n, ymin))) + \
    list(zip(np.full(n, xmin), np.linspace(ymin, ymax, n)))
)
ax.set_boundary(aoi, transform=ccrs.PlateCarree())

# Plot Ocean Borders
ocean = cf.NaturalEarthFeature('physical', 'ocean', scale='50m', edgecolor='k', facecolor='lightblue', lw=1,
                               linestyle='-')
ax.add_feature(ocean)
# Colored Land Background
land = cf.NaturalEarthFeature('physical', 'land', scale='50m', facecolor='snow', lw=1, linestyle='--')
ax.add_feature(land)

ax.set_extent([xmin, xmax, ymin, ymax], crs=ccrs.PlateCarree())
# Set gridlines to variable so you can manipulate them
gl = ax.gridlines(draw_labels=True, crs=ccrs.PlateCarree(), x_inline=False, y_inline=False)
gl.xlocator = mticker.FixedLocator([-160, -150, -140, -130, -120])
gl.ylocator = mticker.FixedLocator([50, 55, 60, 65, 70])
gl.top_labels = False
gl.right_labels = False

plt.show()

问题原因

当使用ax.set_boundary()自定义地图边界后,Cartopy内置的网格线标签位置判定逻辑会出现偏差——原本应被识别为"右侧"的纬度标签,因自定义边界的形状被误判为其他位置的标签,导致right_labels=False的设置失效。

解决方案

通过手动遍历并过滤标签的方式,强制隐藏右侧的纬度标签。在原代码的网格线设置部分添加以下代码:

gl = ax.gridlines(draw_labels=True, crs=ccrs.PlateCarree(), x_inline=False, y_inline=False)
gl.xlocator = mticker.FixedLocator([-160, -150, -140, -130, -120])
gl.ylocator = mticker.FixedLocator([50, 55, 60, 65, 70])
gl.top_labels = False
gl.right_labels = False

# 手动过滤右侧纬度标签
for label in gl.ylabels:
    # 以画布宽度的95%为阈值,判定是否为右侧标签,可根据需求调整
    if label.get_position()[0] > ax.get_window_extent().width * 0.95:
        label.set_visible(False)

说明

该方法通过直接检查纬度标签在画布上的x坐标位置,判断其是否属于右侧区域,然后强制设置为不可见,绕过了Cartopy自身标签判定的问题。如果阈值不合适,可以根据实际地图的显示效果调整0.95这个数值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 13:58:12