使用频率计数绘制概率密度函数

5

我想将拟合的分布转换为频数。

import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
%matplotlib notebook

# sample data generation
np.random.seed(42)
data = sorted(stats.lognorm.rvs(s=0.5, loc=1, scale=1000, size=1000))

# fit lognormal distribution
shape, loc, scale = stats.lognorm.fit(data, loc=0)
pdf_lognorm = stats.lognorm.pdf(data, shape, loc, scale)

fig, ax = plt.subplots(figsize=(8, 4))

ax.hist(data, bins='auto', density=True)
ax.plot(data, pdf_lognorm)
ax.set_ylabel('probability')
ax.set_title('Linear Scale')

上面的代码片段将生成以下图表:

enter image description here

如您所见,y轴是以概率为单位的。但我想要它按照频率来显示。

fig, ax = plt.subplots(figsize=(8, 4))
ax.hist(data, bins='auto')
ax.set_ylabel('probability')
ax.set_title('Linear Scale')

通过取消density=True,直方图将以频率显示。但是我不知道如何像在直方图中那样拟合分布-请注意我无法在此直方图中绘制橙色拟合线。

enter image description here

我该怎么做?我认为应该将拟合分布乘以直方图曲线下的面积,但我不知道如何操作。

2个回答

2

从科学角度来看,如果您决定绘制密度图,那么y轴应该是概率,而不是计数...

然而,您可以使用双轴和twinx同时拥有两者:

最初的回答:

fig, ax = plt.subplots(figsize=(8, 4))
ax2 = ax.twinx()

ax.hist(data, bins='auto', density=True)
ax2.hist(data, bins='auto')
ax.plot(data, pdf_lognorm)
ax2.set_ylabel('frequency')
ax.set_ylabel('probability')
ax.set_title('Linear Scale')][1]][1]

这里输入图片描述

在计数方面,我还使用了更合适的术语“频率”。

通过一些实验,您甚至可以将密度曲线置于前面或交换轴:

fig, ax = plt.subplots(figsize=(8, 4))
ax2 = ax.twinx()

ax2.hist(data, bins='auto', density=True)
ax.hist(data, bins='auto')
ax2.plot(data, pdf_lognorm)
ax2.set_ylabel('probability')
ax.set_ylabel('frequency')
ax.set_title('Linear Scale')

enter image description here


1
我遇到了相同的问题,发现需要像你提到的那样将拟合分布乘以新直方图的面积。假设所有的箱子具有相同的宽度,则直方图的面积将等于直方图一个箱子的宽度(bin width)* 样本数(len(data))。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接