numpymatplotlibnancolormapcartopy

How can I get pcolor to plot NaN values in white while using cartopy?


I am plotting some integer-valued labels on an ocean map using cartopy and pcolor in python. I would like the NaN values to show up as white patches. However, at present, the NaN values are plotted using the lowest color in the colormap. How can I get pcolor to display NaN values in white?

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

I have tried adjusting the colormap using functions like cmap.set_bad, but so far I cannot get this to work. I also tried using a masked array, but it also didn't work. I have included some self-contained example code below that reproduces the problem, at least in my environment.

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()

I would like NaN values to be indicated by a white color, but at present they plot in a color from the colormap. Thanks in advance for any help/guidance.


Solution

  • your code works for me, I get white values instead of a color.

    I'm using numpy 1.15.0, mpl 2.2.2 and cartopy 0.16.0

    on a mac.