如何在不改变颜色映射的情况下,让颜色条从数值0开始显示?

编程语言 2026-07-12

我对颜色条的限制有一个问题。 在我的第一张图中,我想把气候数据的取值从零显示到最大值;在我的第二张图中,则从最小值显示到最大值。不幸的是,在不改变着色的前提下,我没法调整它,这会让两张图的可比性受到影响。换句话说,我希望将0的位置保持为淡蓝色,例如。使用set_clim时,颜色条不会移动。

all_values = np.concatenate([fSA_fut.flatten(), fSA_diff.flatten()])
vmin = np.percentile(all_values, 5)
vmax = np.percentile(all_values, 95)
levels = np.arange(np.floor(vmin/5)*5, np.ceil(vmax/5)*5 + 5, 5)


fig1,ax1=plt.subplots()
VSA_fut_masked = np.ma.masked_less(fSA_fut, 0)
norm= mcolors.BoundaryNorm(levels, ncolors=256)
im=ax1.pcolormesh(lon_fut,lat_fut,fSA_fut_masked, cmap='RdBu_r',norm=norm)
#im.set_clim(0.0, vmax)
cbar = fig1.colorbar(im, orientation='vertical')
cbar.set_label("fSA in doys")
ax1.set_xlabel("longitude in degrees north")
ax1.set_ylabel("Latitude in degrees east")
ax1.set_title('Ensemble-time mean of fSA for RCP 8.5 Scenario 2036-2065')
ax1.set_xlim(-13,35)
ax1.set_ylim(28,70)

fig2,ax2=plt.subplots()
norm=mcolors.BoundaryNorm(levels, ncolors=256)
im2=ax2.pcolormesh(lon_fut,lat_fut,fSA_diff, cmap='RdBu_r',norm=norm)
cbar2 = fig2.colorbar(im2,orientation='vertical')
cbar2.set_label("\Delta fSA in doys")
ax2.set_xlabel("longitude in degrees north")
ax2.set_ylabel("Latitude in degrees east")
ax2.set_title('Difference between Ensemble-time mean \n of fSA 2036-2065 and single-point value in reference-scenario')
ax2.set_xlim(-13,35)
ax2.set_ylim(28,70)
plt.show()

解决方案

你可以做成类似这样的:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

# Generate data to display
shape = (16, 16)
data = np.random.standard_normal(shape)
data_masked = np.ma.masked_less(data, 0)

# Get levels
vmin = np.percentile(data, 5)
vmax = np.percentile(data, 95)

# Get colorbar
cmap = mpl.colormaps['RdBu_r']

# Display
plt.close('all')
fig, (ax0, ax1) = plt.subplots(1, 2, sharey=True)

ax0.set_title('full')
imobj0 = ax0.pcolormesh(data, cmap=cmap)
imobj0.set_clim(vmin, vmax)

ax1.set_title('masked')
imobj1 = ax1.pcolormesh(data_masked, cmap=cmap)
imobj1.set_clim(vmin, vmax)

fig.colorbar(imobj1, ax=[ax0, ax1], orientation='horizontal')
fig.show()

我只用 set_clim,就行。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章