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

问题描述 投票:3回答:1

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

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

我怎样才能做到这一点?我想我应该将拟合分布乘以直方图曲线下面积,但我不知道如何。

python matplotlib statistics distribution probability-density
1个回答
1
投票

从科学上讲,确实预计,由于你决定也绘制密度,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]

enter image description here

在那里我还使用了更合适的术语“频率”来计算。

尝试一点你甚至可以将密度曲线放在前面,或者交换轴:

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

© www.soinside.com 2019 - 2024. All rights reserved.