Problems with zeros in matplotlib.colors.LogNorm

Till Hoffmann picture Till Hoffmann · Feb 26, 2012 · Viewed 9.1k times · Source

I am plotting a histogram using

plt.imshow(hist2d, norm = LogNorm(), cmap = gray)

where hist2d is a matrix of histogram values. This works fine except for elements in hist2d that are zero. In particular, I obtain the following image

Histogram

but would like the white patches to be black.

Thank you!

Answer

tacaswell picture tacaswell · Feb 1, 2013

Here's an alternative method that does not require you to muck with your data by setting a rgb value for bad pixels.

import copy
data = np.arange(25).reshape((5,5))
my_cmap = copy.copy(matplotlib.cm.get_cmap('gray')) # copy the default cmap
my_cmap.set_bad((0,0,0))
plt.imshow(data, 
           norm=matplotlib.colors.LogNorm(), 
           interpolation='nearest', 
           cmap=my_cmap)

The problem is that bins with 0 can not be properly log normalized so they are flagged as 'bad', which are mapped to differently. The default behavior is to not draw anything on those pixels. You can also specify what color to draw pixels that are over or under the limits of the color map (the default is to draw them as the highest/lowest color).