为什么归一化直方图给出错误的 y 值(所有值加起来应该为 1)? Python matplotlib

Why does the normalized histogram give wrong y values (all should add up to 1)? Python matplotlib

试图制作一个简单的直方图(有效)但是在归一化(密度=1)时 - 它给出了不正确的 y 值,因为所有值加起来应该为 1

Dataset = [10,10.2,10.4,10.6,10.8,11.0,11.2]
Freqset = [1,3,7,9,6,5,2]
data =[]

for i in range(len(Dataset)):
    for j in range(Freqset[i]):
        data.append(Dataset[i])
print(data)

bins = len(Dataset)
plt.hist(data,bins,histtype='bar', density = 1,rwidth=0.8,alpha=0.5)

plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title(f'Histogram')

plt.show()

density 关键字参数设置为 True 时,输出直方图由每个 bin 计数的总和归一化,因此可以将其解释为概率密度。

发现于pyplot.hist()documentation:

If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1.

所以不是值加起来应该是 1,而是积分(考虑到 bin 大小)。在您的情况下,bin 大小为 (max(Dataset) - min(Dataset)) / 7 = 0.1714,因此您需要将直方图值乘以 0.1714,总和为 1。

感谢您提供的信息 - 执行建议时遇到一些困难,但我会继续努力。我发现最简单的(目前)是简单地创建一个具有相对频率的列表:

import matplotlib.pyplot as plt

Dataset = [1350,1400,1450,1500,1550,1600,1650]
Freqset = [2,5,8,60,19,3,3]
Relativef = []

for i in range(len(Dataset)):
    Relativef.append(Freqset[i]/sum(Freqset))

print(f"Rel f: {Relativef}")
print(len(Relativef))

bins = len(Dataset)

plt.hist(Dataset,bins,weights=Relativef,rwidth=0.8, alpha=0.5)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.title('Normalized Histogram')

plt.show()