How can I draw NaN values ​​as a special color with imshow in matplotlib?

I am trying to use imshow in matplotlib to plot data as a heat map, but some of them are NaN. I would like NaNs to appear as a special color not found in the color palette.

Example:

import numpy as np import matplotlib.pyplot as plt f = plt.figure() ax = f.add_subplot(111) a = np.arange(25).reshape((5,5)).astype(float) a[3,:] = np.nan ax.imshow(a, interpolation='nearest') f.canvas.draw() 

The resulting image suddenly turns blue (the lowest color in the color map of the jet). However, if I do this:

 ax.imshow(a, interpolation='nearest', vmin=0, vmax=24) 

- then I get something better, but the NaN values ​​are drawn in the same color as vmin ... Is there an elegant way that I can set NaNs using a special color (for example: gray or transparent)?

+64
python matplotlib nan
Apr 05 2018-10-14T00:
source share
3 answers

Hrm, it looks like I can use a masked array for this:

 masked_array = np.ma.array (a, mask=np.isnan(a)) cmap = matplotlib.cm.jet cmap.set_bad('white',1.) ax.imshow(masked_array, interpolation='nearest', cmap=cmap) 

That should be enough, although I'm still open to suggestions.:]

+64
Apr 05 '10 at 14:30
source share

With newer versions of Matplotlib you no longer need to use a masked array.

For example, let's generate an array where every 7th value is NaN:

 arr = np.arange(100, dtype=float).reshape(10, 10) arr[~(arr % 7).astype(bool)] = np.nan 

We can change the current color code and build an array with the following lines:

 current_cmap = matplotlib.cm.get_cmap() current_cmap.set_bad(color='red') plt.imshow(arr) 

plot result

+13
Oct 09 '17 at 14:40
source share

This did not work for me. I received an error message, as well as a workaround:

 a[3,:] = -999 masked_array=np.ma.masked_where(a==-999, a) cmap = matplotlib.cm.jet cmap.set_bad('w',1.) ax.imshow(masked_array, interpolation='nearest', cmap=cmap) 
+4
May 7 '12 at 12:01
source share



All Articles