문제

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!

도움이 되었습니까?

해결책

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).

다른 팁

If you're happy with the colour scaling as is, and simply want the 0 values to be black, I'd simply change the input matrix so that the 0s are replaced by the next smallest value:

import matplotlib.pyplot as plt
import matplotlib.cm, matplotlib.colors
import numpy

hist2d = numpy.arange(9).reshape(3,3)

plt.imshow(numpy.maximum(hist2d, sorted(hist2d.flat)[1]), 
           interpolation='nearest', 
           norm = matplotlib.colors.LogNorm(), 
           cmap = matplotlib.cm.gray)

produces

0- loading=mimimum picture">

Was this generated with the matplotlib hist2d function?

All you need to do is go through the matrix and set some arbitrary floor value, then make sure to plot this with fixed limits

for f in hist2d:
   f += 1e-3

then when you show the figure, all of the whitespace will now be at the floor value, and will show up on the lognormal plot . However, if you are letting hist2d automatically pick the scaling for you, it will want to use the 1e-3 floor value as the minimum. To avoid this, you need to set vmin and vmax values in hist2d

hist2d(x,y,bins=40, norm=LogNorm(), vmin=1, vmax=1e4)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top