F L F L - 4 months ago 34
Python Question

Plot color NaN values

I'm trying to plot color some array, and convert some of the values to np.nan (for easier interpretation) and expecting different color when plotted (white?), instead it causes problem with the plot and the colorbar.

#this is before converted to nan
array = np.random.rand(4,10)
plt.pcolor(array)
plt.colorbar(orientation='horizontal')


normal result

#conditional value converted to nan
array = np.random.rand(4,10)
array[array<0.5]=np.nan
plt.pcolor(array)
plt.colorbar(orientation='horizontal')


conditional result

Any suggestion?

Answer

One of the solution is to plot masked array, like here:

import matplotlib.pylab as plt
import numpy as np

#conditional value converted to nan
array = np.random.rand(4,10)
array[array<0.5]=np.nan
m = np.ma.masked_where(np.isnan(array),array)
plt.pcolor(m)
plt.colorbar(orientation='horizontal')       
plt.show()

enter image description here