2

I've got a numpy array containing both np.nan (missing value) and -9999.0 (or any other arbitrary value=> non calculation possible), e.g.:

arr = array([[ 1.,  2.,  3.,  nan,  4.,  4.],
   [ 3.,  -9999.0,  2.,  1.,  1.,  4.],
   [ nan,  -9999.0,  3.,  1.,  2.,  1.]])

Now I want to plot this array with the plt.imshow function. All NaNs shall be transparent/white and all -9999.0s shall be black, for example. I already tried to mask the array and then use set_bad for the colormap. Beyond that, I used vmin/vmax and cm.set_under. However, in the first case it yields: RuntimeWarning: invalid value encountered in less when I try to mask out all values <9990. In the second case, obviously both the NaNs and -9999.0s are interepreted as below the range of the depicted range of values. Does anyone know help?

user3017048
  • 2,711
  • 3
  • 22
  • 32

2 Answers2

0

It sounded like you said this didn't work for you, but it seemed to work for me. From an ipython notebook cell:

% matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
a = np.array([[ 1.,  2.,  3.,  np.nan,  4.,  4.],
   [ 3.,  -9999.0,  2.,  1.,  1.,  4.],
   [ np.nan,  -9999.0,  3.,  1.,  2.,  1.]])
fig, ax = plt.subplots()
masked_array = np.ma.array (a, mask=np.isnan(a))
cmap = matplotlib.cm.autumn
cmap.set_bad('w',1.)
ax.imshow(masked_array, interpolation='nearest', cmap=cmap)

imgur link since it won't let me post images due to low rep.

Community
  • 1
  • 1
Dan L
  • 83
  • 1
  • 6
  • This works, however, I think it does not consider an extra value for the -9999.0. It simply integrates it into the colormap range. – user3017048 Sep 12 '15 at 12:24
  • Ah, sorry, got thrown off the scent by "All NaNs shall be transparent/white and all -9999.0s shall be black, for example." Read it too quickly. Glad it looks like you figured it out. – Dan L Sep 12 '15 at 12:40
  • Thanks neverthless! :-) – user3017048 Sep 12 '15 at 12:45
0

Okay, the solution is to use BOTH set_under and set_bad:

cm.set_bad('white')
cmap.set_under('black')

The bad value takes care of the NaNs, the set_under sets an extra value for the -9999.0s.

Thanks anyhow for your efforts!

user3017048
  • 2,711
  • 3
  • 22
  • 32