Python:直方图,区域标准化为1以外的值

Paw*_*win 9 python matplotlib histogram area

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

选项"normed = 0"in

n, bins, patches = plt.hist(x, 50, normed=0, histtype='stepfilled')
Run Code Online (Sandbox Code Playgroud)

只是把它带回频率分布.

Joe*_*ton 10

只需计算它并将其标准化为您想要的任何值,然后用于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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

因此,在这种情况下,如果我们要整合(总和高度乘以宽度)的箱子,我们得到2.0而不是1.0.((hist * widths).sum()即将屈服2.0)


Jam*_*mes 8

您可以传递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)
Run Code Online (Sandbox Code Playgroud)

应该做的伎俩.

编辑:weights参数必须与大小相同x,其效果是使x中的每个值都weights为bin计数提供相应的值,而不是1.

不过,我认为该hist函数可能具有更强的控制规范化的能力.例如,我认为,当标准化时,忽略了分箱范围之外的值,这通常不是您想要的.