简体   繁体   English

从numpy数组绘制直方图

[英]Plotting histrogram from numpy array

I need to create histograms from the 2D arrays that I obtain from convolving an input array and a filter. 我需要从对输入数组和过滤器进行卷积获得的2D数组中创建直方图。 The bins should as the range of the values in the array. 垃圾箱应作为数组中值的范围。

I tried following this example: How does numpy.histogram() work? 我尝试按照以下示例进行操作: numpy.histogram()如何工作? The code is this: 代码是这样的:

import matplotlib.pyplot as plt
import numpy as np
plt.hist(result, bins = (np.min(result), np.max(result),1))
plt.show()

I always get this error message: 我总是收到以下错误消息:

AttributeError: bins must increase monotonically.

Thanks for any help. 谢谢你的帮助。

What you are actually doing is specifying three bins where the first bin is np.min(result) , second bin is np.max(result) and third bin is 1 . 您实际上正在执行的操作是指定三个容器,其中第一个容器为np.min(result) ,第二个容器为np.max(result) ,第三个容器为1 What you need to do is provide where you want the bins to be located in the histogram, and this must be in increasing order. 您需要做的是在直方图中提供您要放置垃圾箱的位置,并且该垃圾箱必须以递增的顺序排列。 My guess is that you want to choose bins from np.min(result) to np.max(result) . 我的猜测是您想从np.min(result)np.max(result)选择bin。 The 1 seems a bit odd, but I'm going to ignore it. 1似乎有些奇怪,但我将忽略它。 Also, you want to plot a 1D histogram of values, yet your input is 2D . 另外,您想绘制一维值的直方图,而您的输入是2D If you'd like to plot the distribution of your data over all unique values in 1D, you'll need to unravel your 2D array when using np.histogram . 如果要在1D中绘制所有唯一值上的数据分布,则在使用np.histogram时需要解散 2D数组。 Use np.ravel for that. np.ravel使用np.ravel

Now, I'd like to refer you to np.linspace . 现在,我想向您np.linspace You can specify a minimum and maximum value and as many points as you want in between uniformly spaced. 您可以指定最小和最大值,并在均匀间隔之间指定任意数量的点。 So: 所以:

bins = np.linspace(start, stop)

The default number of points in between start and stop is 50, but you can override this: startstop之间的默认点数是50,但是您可以覆盖此点:

bins = np.linspace(start, stop, num=100)

This means that we generate 100 points in between start and stop . 这意味着我们在startstop之间生成100个点。

As such, try doing this: 因此,请尝试执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM