为什么在带有自定义颜色条的 pcolormesh 和 contourf 图之间显示颜色条的差异

Why is the difference in color bar showing up between pcolormesh and contourf plot with custom made color bar

我根据离散间隔色条 exampleNCL 改编了自定义色标。我的 data-array 在 NetCDF 文件中,当我尝试绘制它时,绘图和颜色条看起来与 pcolormesh 绘图的预期一样,但当我绘制 contourf 绘图时它变得疯狂。我在 定义 色阶时做错了什么吗?

import matplotlib.colors
import xarray as xr

# loading data

ds = xr.open_dataset(path/tofile/data.nc)


## custom color bar
## converting RGB values to 0,1
cmap3 =  matplotlib.colors.ListedColormap([(127/255, 150/255, 255/255), (142/255, 178/255, 255/255), (181/255, 201/255, 255/255), (214/255, 226/255, 237/255),\
(242/255, 221/255, 160/255), (242/255, 132/255, 68/255), (229/255, 0/255, 0/255), (1, 163/255, 10/255), (1, 249/255, 20/255), (172/255, 206/255, 100/255), (125/255, 190/255, 84/255)])

# I want to discretize the colorbar according to values
vals = [-1.0, 0.0, 0.2 ,0.5, 0.8, 1.0, 1.5, 2.0, 4.0 , 6.0 , 8.0,  10]
norm = matplotlib.colors.BoundaryNorm(vals, cmap3.N)

# variable to be plotted
ds.PV.squeeze().plot.pcolormesh(cmap=cmap3, norm=norm, vmin=0, vmax=10)
# contourf plot which is giving unexpected result
ds.PV.squeeze().plot.contourf(cmap=cmap3, norm=norm, vmin=0, vmax=10)

使用 Pcolormesh 图的预期色标:

绘制 contourf 图时色标错误:

下面是带有默认色标的 contourf 图

这就是我的正确 颜色条的样子:

fig, ax =plt.subplots(figsize=(6,1))

cb3 = matplotlib.colorbar.ColorbarBase(ax, cmap=cmap3,
                            norm=norm,
                            extend='neither',
                            ticks=vals,
                            spacing='uniform',
                            orientation='horizontal')    

@ImportanceofBeingErnest this 详细的回答很有帮助。在 contourf 中,必须具体指定需要绘制轮廓的级别,而 pcolormesh 似乎会根据颜色栏自动选择它

ds.PV.squeeze().plot.contourf(cmap=cmap3, norm=norm,levels=vals)