Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to use imshow in matplotlib to plot data as a heatmap, but some of the values are NaNs. I'd like the NaNs to be rendered as a special color not found in the colormap.

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 resultant image is unexpectedly all blue (the lowest color in the jet colormap). However, if I do the plotting like this:

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

--then I get something better, but the NaN values are drawn the same color as vmin... Is there a graceful way that I can set NaNs to be drawn with a special color (eg: gray or transparent)?

like image 796
Adam Fraser Avatar asked Apr 05 '10 14:04

Adam Fraser


People also ask

How do I change my color on PLT Imshow?

The most direct way is to just render your array to RGB using the colormap, and then change the pixels you want.

Can we select Colours of the visualization using matplotlib?

With matplotlibscatter a c argument, which allows you to select the colors.


1 Answers

Hrm, it appears I can use a masked array to do 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) 

This should suffice, though I'm still open to suggestions. :]

like image 63
Adam Fraser Avatar answered Oct 18 '22 01:10

Adam Fraser