matplotlib 在使用Cartopy时,如何让pcolor以白色绘制NaN值?

hs1rzwqc  于 2023-03-09  发布在  其他
关注(0)|答案(2)|浏览(205)

我在python中使用Cartopy和pcolor在海洋Map上绘制一些整数值标签。我希望NaN值显示为白色补丁。然而,目前NaN值是使用颜色图中最低的颜色绘制的。我如何让pcolor以白色显示NaN值?
Here is an example map where pcolor displays NaN values using a color, instead of white
我试过使用cmap.set_bad这样的函数来调整色彩Map表,但到目前为止我还不能让它工作。我也试过使用掩码数组,但它也不起作用。我在下面包含了一些自包含的示例代码,它们至少在我的环境中重现了这个问题。

import numpy as np
import matplotlib as mpl
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
from random import seed
from random import randint

## set maximum number of integer labels
n_comp = 4

# generate random integer "labels" as example data 
seed(1)
labels = np.zeros((128*64,1))
for ncomp in range(0, 64*128-1):
    labels[ncomp] = randint(0, n_comp)

# make array 2D for plotting
labels2D = labels.reshape((128,64))

# replace zero with nan
labels2D[labels2D==0] = np.nan

# create latitude / longitude data
x = np.arange(0.0,360.0,2.815)
xx = np.tile(x,[64,1])
xx = xx.transpose()
y = np.arange(-90,90,2.815)
yy = np.tile(y,[128,1])

# create figure and axes
fig = plt.figure(figsize=(10, 5))
ax = fig.add_subplot(1, 1, 1, 
                     projection=ccrs.Robinson(central_longitude=-150))

# create colormap 
cmap=plt.get_cmap('Accent', n_comp+1)

# use white color to mark 'bad' values
cmap.set_bad(color='w')

# use norm to define colormap
boundaries = np.arange(0.5,n_comp+1,1)
norm = mpl.colors.BoundaryNorm(boundaries, cmap.N, clip=True)

# use pcolor to make label map
labelMap = ax.pcolor(xx, yy, labels2D,
                     transform=ccrs.PlateCarree(), 
                     norm=norm, 
                     cmap=cmap,
                     vmin = 1,
                     vmax = n_comp)

# add continents on top of label data
ax.add_feature(cfeature.LAND, zorder=1, edgecolor='black')

# plot colorbar with ticks at centres of bars
plt.colorbar(labelMap, ticks=np.arange(1,n_comp+1,1))

# show plot 
plt.show()

我想用白色来表示NaN值,但目前它们是用颜色Map表中的颜色来绘制的。感谢您的帮助/指导。

qkf9rpyu

qkf9rpyu1#

你的代码对我有用,我得到白色值而不是颜色。
我使用的是麻醉1.15.0、MPL 2.2.2和心血管造影0.16.0
在苹果电脑上。

v1uwarro

v1uwarro2#

cmap.set_bad(color='w')也为我工作,当做:

pcolormesh(data, norm=colors.LogNorm(vmin=vmin, vmax=vmax))

但在使用norm=colors.SymLogNorm()时不起作用

相关问题