我需要从2D阵列创建直方图,这是通过卷积输入数组和滤波器获得的。这些箱子应该作为数组中值的范围。
我尝试过以下示例:How does numpy.histogram() work? 代码是这样的:
import matplotlib.pyplot as plt
import numpy as np
plt.hist(result, bins = (np.min(result), np.max(result),1))
plt.show()
我总是收到此错误消息:
AttributeError: bins must increase monotonically.
感谢您的帮助。
答案 0 :(得分:2)
你实际在做的是指定三个箱子,其中第一个箱子是np.min(result)
,第二个箱子是np.max(result)
,第三个箱子是1
。您需要做的是提供您希望柱子位于直方图中的位置,并且必须按升序排列。我的猜测是,您要从np.min(result)
到np.max(result)
选择分类。 1似乎有点奇怪,但我会忽略它。此外,您想要绘制一维值的直方图,但输入是2D 。如果您想在1D中绘制数据在所有唯一值上的分布,则在使用np.histogram
时,您需要解开您的2D数组。请使用np.ravel
。
现在,我想推荐你np.linspace
。您可以在均匀间隔之间指定最小值和最大值以及所需的点数。所以:
bins = np.linspace(start, stop)
start
和stop
之间的默认点数为50,但您可以覆盖此项:
bins = np.linspace(start, stop, num=100)
这意味着我们会在start
和stop
之间生成100个点。
因此,请尝试这样做:
import matplotlib.pyplot as plt
import numpy as np
num_bins = 100 # <-- Change here - Specify total number of bins for histogram
plt.hist(result.ravel(), bins=np.linspace(np.min(result), np.max(result), num=num_bins)) #<-- Change here. Note the use of ravel.
plt.show()