ax.hist不输出与np.histogram相同

时间:2018-02-25 06:02:29

标签: python numpy matplotlib

我不确定这是不是错误,但是我无法使用ax.hist生成直方图。当我尝试使用ax.hist绘制numpy.nd.array时,我会看到一张空白图表。在调查返回的列表和箱子时,列表都是0,不应该是这种情况。当我使用numpy.histogram()输出值和列表列表时,我会显示正确的值,并能够使用ax.bar()绘制我需要的内容。此外,我还使用skimage.expose.histogram进行了检查,其返回的内容与numpy.histogram()相同

为了完整性,我用skimage.io加载以下图像并尝试绘制显示每个通道颜色强度的直方图。代码是:

import matplotlib.pyplot as plt
import numpy as np    
import skimage
from skimage import io, color

img = io.imread(MY_IMAGE_PATH)
print(type(img)) # numpy.nd.array
print(img.shape) # (256, 256, 4)

fig = plt.figure(figsize=(10, 10))
grid_size = (1, 1)

ax1 = plt.subplot2grid(grid_size, (0, 0), rowspan=1, colspan=1)
# hist, bins = skimage.exposure.histogram(img[:, :, 0])
# ax1.bar(bins, hist, width=1, color="red")
n, bins, _ = ax1.hist(img[:, :, 0].ravel(), bins=256, range=(0.0, 1.0), color="white") # Red channel
ax.set_facecolor((44/255, 53/255, 57/255)) # dark gray background
values, np_bins = np.histogram(img[:, :, 0].ravel()

我正在加载的图片:enter image description here

我有一个解决方法,但我想知道问题是否与我的代码有关,或者这确实是一个错误?

1 个答案:

答案 0 :(得分:1)

  1. 在白色背景上绘制白条将使它们不可见。使用其他颜色,例如color="red"
  2. 如果直方图的值介于0到255之间,则将值的范围设置为(0,1)是没有意义的。而是使用range=(0, 255)