从 numpy 数组绘制直方图
Plotting histrogram from numpy array
我需要根据对输入数组和滤波器进行卷积得到的二维数组创建直方图。箱子应该作为数组中值的范围。
我试着按照这个例子做: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.
感谢您的帮助。
您实际做的是指定三个 bin,其中第一个 bin 是 np.min(result)
,第二个 bin 是 np.max(result)
,第三个 bin 是 1
。你需要做的是提供你希望 bins 在直方图中的位置,并且这个 必须 是递增的顺序。我的猜测是您想选择从 np.min(result)
到 np.max(result)
的 bin。 1 看起来有点奇怪,但我会忽略它。此外,您想要绘制值的一维直方图,但您的 输入是二维的 。如果您想绘制一维数据在所有唯一值上的分布,则在使用 np.histogram
时需要 展开 二维数组。为此使用 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()
我需要根据对输入数组和滤波器进行卷积得到的二维数组创建直方图。箱子应该作为数组中值的范围。
我试着按照这个例子做: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.
感谢您的帮助。
您实际做的是指定三个 bin,其中第一个 bin 是 np.min(result)
,第二个 bin 是 np.max(result)
,第三个 bin 是 1
。你需要做的是提供你希望 bins 在直方图中的位置,并且这个 必须 是递增的顺序。我的猜测是您想选择从 np.min(result)
到 np.max(result)
的 bin。 1 看起来有点奇怪,但我会忽略它。此外,您想要绘制值的一维直方图,但您的 输入是二维的 。如果您想绘制一维数据在所有唯一值上的分布,则在使用 np.histogram
时需要 展开 二维数组。为此使用 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()