在python中集成直方图? [英] Integrate histogram in python?
问题描述
matplotlib 中是否有一个简单的命令可以让我在某个范围内对直方图进行积分?如果我绘制一个直方图:fig = plt.hist(x, bins)那么,有没有像 fig.integral(bin1, bin2) 这样的命令?那将返回从 bin1 到 bin2 的直方图的积分?
Is there a simple command in matplotlib that let's me take the integral of histogram over a certain range? If I plot a histogram with: fig = plt.hist(x, bins) Then, is there a command like fig.integral(bin1, bin2)? That will return the integral of the histogram from bin1 to bin2?
推荐答案
首先,请记住积分只是曲线下方的总面积.在直方图的情况下,积分(在伪python中)是sum([bin_width[i] * bin_height[i] for i in bin_indexes_to_integrate])
.
First, remember that the integral is just the total area underneath the curve. In the case of a histogram, the integral (in pseudo-python) is sum([bin_width[i] * bin_height[i] for i in bin_indexes_to_integrate])
.
作为参考,请参阅在 matplotlib 中使用直方图的示例:http://matplotlib.org/1.2.1/examples/pylab_examples/histogram_demo.html.
As a reference, see this example of using a histogram in matplotlib: http://matplotlib.org/1.2.1/examples/pylab_examples/histogram_demo.html.
这里他们将 plt.histogram
的输出分成三部分,n
、bins
和 patches
>.我们可以使用这种分离来实现您像这样要求的积分".
Here they separate the output of the plt.histogram
into three parts, n
, bins
, and patches
. We can use this separation to implement the "integral" you request like so.
假设 bin1
和 bin2
是要积分的 bin 的索引,然后像这样计算积分:
Assuming bin1
and bin2
are indexes of the bins you want to integrate, then calculate the integral like so:
# create some dummy data to make a histogram of
import numpy as np
x = np.random.randn(1000)
nbins = 10
# use _ to assign the patches to a dummy variable since we don't need them
n, bins, _ = plt.hist(x, nbins)
# get the width of each bin
bin_width = bins[1] - bins[0]
# sum over number in each bin and mult by bin width, which can be factored out
integral = bin_width * sum(n[bin1:bin2])
如果您已将 bins
定义为具有多个宽度的列表,则您必须执行类似于 @cphlewis 所说的操作(此操作没有一个关闭):
If you've defined bins
to be a list with multiple widths, you have to do something like what @cphlewis said (this works w/ no off by one):
integral = sum(np.diff(bins[bin1:bin2])*n[bin1:bin2])
还值得一看 matplotlib.pyplot.hist 的 API 文档.
这篇关于在python中集成直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!