Python:面积规格化为1以外的直方图

2024-04-25 04:17:33 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法告诉matplotlib“规范化”直方图,使其面积等于指定值(1除外)?

选项“normed=0”

n, bins, patches = plt.hist(x, 50, normed=0, histtype='stepfilled')

回到频率分布。


Tags: matplotlib选项plt直方图规范化hist频率面积
2条回答

您可以将weights参数传递给hist,而不是使用normed。例如,如果您的存储箱覆盖间隔[minval, maxval],那么您有n存储箱,并且您希望将区域规范化为A,那么我认为

weights = np.empty_like(x)
weights.fill(A * n / (maxval-minval) / x.size)
plt.hist(x, bins=n, range=(minval, maxval), weights=weights)

应该会成功的。

编辑:参数weights的大小必须与x的大小相同,其效果是使x中的每个值向bin计数贡献weights中的相应值,而不是1。

不过,我认为hist函数可能需要更强的控制规范化的能力。例如,我认为按现状,在规格化时忽略binned范围之外的值,这通常不是您想要的。

只需计算它并将其规格化为您想要的任何值,然后使用bar绘制直方图。

另一方面,这将规范化所有条的区域normed_value。原始和将不是normed_value(尽管如果您愿意的话,很容易做到这一点)。

例如

import numpy as np
import matplotlib.pyplot as plt

x = np.random.random(100)
normed_value = 2

hist, bins = np.histogram(x, bins=20, density=True)
widths = np.diff(bins)
hist *= normed_value

plt.bar(bins[:-1], hist, widths)
plt.show()

enter image description here

所以,在这种情况下,如果我们要积分(高度和宽度之和),我们得到的是2.0而不是1.0。(即(hist * widths).sum()将产生2.0

相关问题 更多 >