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

标签 python matplotlib statistics distribution probability-density

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

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

我该怎么做?我想我应该将拟合分布与直方图曲线下的面积相乘,但我不知道该怎么做。

最佳答案

从科学上讲,确实可以预期,因为您决定也绘制密度,所以 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

关于python - 用频率计数绘制概率密度函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54877858/

相关文章:

python - 快速计算节点到节点集的距离

python - 是否有用于训练对数线性模型的 python 包?

Python 绘图 : Heatmap from dataframe with fixed colors in case of strings

python - 如何在 networkx 图形绘图中显示循环

python - 如何使用 pyplot 正确显示图像的红色、绿色和蓝色 (rgb) channel

machine-learning - 使用机器学习根据传感器数据进行故障预测

python - 使用 Django 模型创建子类别

python - pandas/matplotlib 具有多个 y 轴的图

math - 如何获得趋势的标准化斜率

php - 基于MySQL和PHP的统计