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

Matplotlib中Subplot的Y轴标签无法显示,原因是什么?

解决Matplotlib+Cartopy子图Y轴标签不显示的问题

问题原因

Y轴标签无法显示主要有两个核心原因:

  1. Cartopy投影轴特性:用projection=proj创建的GeoAxes不会默认显示Matplotlib原生的set_ylabel()标签,它有独立的坐标轴标注逻辑。
  2. 共享轴的影响:设置sharey=True后,除第一列第一个子图外,其他子图的Y轴标签会被自动隐藏,避免重复显示。

解决方案

以下提供两种可行的修改方式,结合你的代码调整:

方案1:显示Cartopy原生纬度标签(推荐)

利用Cartopy的坐标轴工具手动设置Y轴(纬度)的刻度和标签,适配投影系统:

nc=21 #number of subplot columns

import cartopy.crs as ccrs
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(nc*2, 15, 29)

title_list = ['elnino', 'neutral',]

proj = ccrs.PlateCarree(central_longitude=180, globe=None)
kwargs_pcol = dict(cmap=plt.cm.RdBu_r, transform=ccrs.PlateCarree())
lats = np.linspace(-90, 90, data.shape[1])
longs = np.linspace(-180, 180, data.shape[2])

fig, axs = plt.subplots(nrows=nc, ncols=2, subplot_kw=dict(projection=proj), figsize=(12, 48), sharex=True, sharey=True)

for i, (ax, data_slice) in enumerate(zip(axs.T.ravel().flat, data)):
    ax.coastlines()
    # 简化重复的pcolormesh代码
    p = ax.pcolormesh(longs, lats, data_slice, shading='auto', vmin=0, vmax=1, **kwargs_pcol)
    cbar = plt.colorbar(p, ax=ax)
    
    if i % nc == 0:
        ax.set_title(f"{title_list[int(i/nc)]}_{i}")
    
    # 设置Y轴(纬度)刻度和标签
    ax.set_yticks(np.arange(-90, 91, 30), crs=ccrs.PlateCarree())
    ax.set_ylabel('纬度', fontsize=10)

plt.subplots_adjust(wspace=0.02, hspace=0.1)
plt.show()

方案2:手动添加自定义标签(适配共享轴)

如果需要显示自定义的Y标签,且不想重复显示,可通过轴坐标定位,仅给每列第一个子图添加标签:

nc=21 #number of subplot columns

import cartopy.crs as ccrs
import numpy as np
import matplotlib.pyplot as plt
data = np.random.rand(nc*2, 15, 29)

title_list = ['elnino', 'neutral',]

proj = ccrs.PlateCarree(central_longitude=180, globe=None)
kwargs_pcol = dict(cmap=plt.cm.RdBu_r, transform=ccrs.PlateCarree())
lats = np.linspace(-90, 90, data.shape[1])
longs = np.linspace(-180, 180, data.shape[2])

fig, axs = plt.subplots(nrows=nc, ncols=2, subplot_kw=dict(projection=proj), figsize=(12, 48), sharex=True, sharey=True)

for i, (ax, data_slice) in enumerate(zip(axs.T.ravel().flat, data)):
    ax.coastlines()
    p = ax.pcolormesh(longs, lats, data_slice, shading='auto', vmin=0, vmax=1, **kwargs_pcol)
    cbar = plt.colorbar(p, ax=ax)
    
    if i % nc == 0:
        ax.set_title(f"{title_list[int(i/nc)]}_{i}")
        # 仅给每列第一个子图添加自定义Y标签
        ax.text(-0.1, 0.5, 'Y', va='center', ha='center', rotation='vertical', transform=ax.transAxes, fontsize=10)

plt.subplots_adjust(wspace=0.02, hspace=0.1)
plt.show()

关键修改说明

  • 方案1中,set_yticks()需指定crs=ccrs.PlateCarree(),确保刻度值对应正确的地理坐标,Cartopy会自动处理标签显示。
  • 方案2中,ax.text()使用ax.transAxes坐标系(轴自身的相对坐标),将标签固定在轴左侧中间位置,不受共享轴设置影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 18:32:00