注意
转到末尾 下载完整示例代码。
累积分布#
本示例展示如何绘制样本的经验累积分布函数(ECDF)。我们还展示了理论CDF。
在工程领域,ECDF有时被称为“非超限”曲线:给定x值的y值表示样本中观测值低于该x值的概率。例如,x轴上220的值对应y轴上约0.80,因此样本中观测值不超过220的概率为80%。相反,经验互补累积分布函数(ECCDF,或“超限”曲线)显示了样本中观测值高于x值的概率y。
绘制ECDF的直接方法是 Axes.ecdf
。传入 complementary=True
会得到ECCDF。
另一种方法是使用 ax.hist(data, density=True, cumulative=True)
,首先对数据进行分箱,如同绘制直方图一样,然后计算并绘制每个箱中条目频率的累积和。在这里,要绘制ECCDF,请传入 cumulative=-1
。请注意,这种方法会得到E(C)CDF的近似值,而 Axes.ecdf
则是精确的。
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
mu = 200
sigma = 25
n_bins = 25
data = np.random.normal(mu, sigma, size=100)
fig = plt.figure(figsize=(9, 4), layout="constrained")
axs = fig.subplots(1, 2, sharex=True, sharey=True)
# Cumulative distributions.
axs[0].ecdf(data, label="CDF")
n, bins, patches = axs[0].hist(data, n_bins, density=True, histtype="step",
cumulative=True, label="Cumulative histogram")
x = np.linspace(data.min(), data.max())
y = ((1 / (np.sqrt(2 * np.pi) * sigma)) *
np.exp(-0.5 * (1 / sigma * (x - mu))**2))
y = y.cumsum()
y /= y[-1]
axs[0].plot(x, y, "k--", linewidth=1.5, label="Theory")
# Complementary cumulative distributions.
axs[1].ecdf(data, complementary=True, label="CCDF")
axs[1].hist(data, bins=bins, density=True, histtype="step", cumulative=-1,
label="Reversed cumulative histogram")
axs[1].plot(x, 1 - y, "k--", linewidth=1.5, label="Theory")
# Label the figure.
fig.suptitle("Cumulative distributions")
for ax in axs:
ax.grid(True)
ax.legend()
ax.set_xlabel("Annual rainfall (mm)")
ax.set_ylabel("Probability of occurrence")
ax.label_outer()
plt.show()

参考
本示例展示了以下函数、方法、类和模块的使用
脚本总运行时间: (0 分 1.422 秒)