numpy直方图累积密度不总和为1

J K*_*lly 12 python numpy

从另一个线程(@ EnricoGiampieri累积分布图python 的回答)中提示,我写道:

# plot cumulative density function of nearest nbr distances
# evaluate the histogram
values, base = np.histogram(nearest, bins=20, density=1)
#evaluate the cumulative
cumulative = np.cumsum(values)
# plot the cumulative function
plt.plot(base[:-1], cumulative, label='data')
Run Code Online (Sandbox Code Playgroud)

我从np.histogram上的文档中输入了密度= 1,其中说:

"请注意,除非选择单位宽度的区间,否则直方图值的总和不会等于1;它不是概率质量函数."

确实,在绘制时,它们并不总和为1.但是,我不理解"统一宽度的箱子".当我将箱子设置为1时,当然,我得到一个空图表; 当我将它们设置为种群大小时,我得不到1(更像是0.2).当我使用建议的40个箱子时,它们的总和大约为.006.

有人可以给我一些指导吗?谢谢!

Pau*_*l H 17

你可以values自己简单地规范你的变量:

unity_values = values / values.sum()

一个完整的例子看起来像这样:

import numpy as np
import matplotlib.pyplot as plt

x = np.random.normal(size=37)
density, bins = np.histogram(x, normed=True, density=True)
unity_density = density / density.sum()

fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, sharex=True, figsize=(8,4))
widths = bins[:-1] - bins[1:]
ax1.bar(bins[1:], density, width=widths)
ax2.bar(bins[1:], density.cumsum(), width=widths)

ax3.bar(bins[1:], unity_density, width=widths)
ax4.bar(bins[1:], unity_density.cumsum(), width=widths)

ax1.set_ylabel('Not normalized')
ax3.set_ylabel('Normalized')
ax3.set_xlabel('PDFs')
ax4.set_xlabel('CDFs')
fig.tight_layout()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


per*_*iae 8

你需要确保你的箱子都是宽度1.这是:

np.all(np.diff(base)==1)
Run Code Online (Sandbox Code Playgroud)

要实现此目的,您必须手动指定垃圾箱:

bins = np.arange(np.floor(nearest.min()),np.ceil(nearest.max()))
values, base = np.histogram(nearest, bins=bins, density=1)
Run Code Online (Sandbox Code Playgroud)

你得到:

In [18]: np.all(np.diff(base)==1)
Out[18]: True

In [19]: np.sum(values)
Out[19]: 0.99999999999999989
Run Code Online (Sandbox Code Playgroud)

  • 从文档:`if \`bins \`是一个int,它定义了给定范围内的等宽二进制数(默认为10)` - 所以OP的例子应该默认工作,不是吗?好像是一个bug. (2认同)