Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set color for NaN values in matplotlib

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?

like image 657
F L Avatar asked Aug 06 '16 04:08

F L


1 Answers

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

like image 150
Serenity Avatar answered Oct 20 '22 04:10

Serenity