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

问题描述 投票:0回答:2

我正在使用 python 中的 cartopy 和 pcolor 在海洋地图上绘制一些整数值标签。我希望 NaN 值显示为白色补丁。但是,目前,NaN 值是使用颜色图中最低的颜色绘制的。如何让 pcolor 以白色显示 NaN 值?

Here is an example map where pcolor displays NaN values using a color, instead of white

我已经尝试使用像 cmap.set_bad 这样的函数来调整颜色图,但到目前为止我无法让它工作。我也尝试过使用掩码数组,但它也没有用。我在下面包含了一些重现问题的独立示例代码,至少在我的环境中是这样。

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 值用白色表示,但目前它们以颜色图中的颜色绘制。在此先感谢您的帮助/指导。

numpy matplotlib nan colormap cartopy
2个回答
1
投票

你的代码对我有用,我得到白色值而不是颜色。

我正在使用 numpy 1.15.0、mpl 2.2.2 和 cartopy 0.16.0

在 Mac 上


0
投票

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

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

但是用的时候没用

norm=colors.SymLogNorm()

© www.soinside.com 2019 - 2024. All rights reserved.