gpt4 book ai didi

python - 在 python 中集成直方图?

转载 作者:太空宇宙 更新时间:2023-11-03 11:50:06 25 4
gpt4 key购买 nike

matplotlib 中是否有一个简单的命令让我在一定范围内对直方图进行积分?如果我绘制直方图: 图 = plt.hist(x, bins)那么,有没有像fig.integral(bin1, bin2)这样的命令呢?那会返回直方图从 bin1 到 bin2 的积分吗?

最佳答案

首先,请记住积分只是曲线下方的总面积。对于直方图,积分(在伪 Python 中)是 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 .

这里他们将plt.histogram的输出分成三部分,nbinspatches。我们可以使用这种分离来实现您要求的“整体”。

假设 bin1bin2 是您要积分的 bin 的索引,然后像这样计算积分:

# 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 所说的操作(这有效,没有一个):

integral = sum(np.diff(bins[bin1:bin2])*n[bin1:bin2]) 

API documentation for matplotlib.pyplot.hist 也值得一看.

关于python - 在 python 中集成直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29974976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com