如何为直方图PDF获取平滑轮廓(带填充区域)及最优拟合曲线?
基于直方图数据生成平滑PDF并拟合最优曲线
问题描述
当前通过plt.hist生成的PDF轮廓不够平滑,需要实现:
- 更平滑的PDF曲线并填充曲线下方区域
- 为数据获取最优拟合曲线
当前使用的代码:
plt.hist( data, range=[0, 60], bins=60, density=True, label="In bulk", histtype="stepfilled", alpha=0.5, )
解决方案
1. 生成平滑PDF并填充区域
用**核密度估计(KDE)**生成平滑曲线,结合matplotlib的填充功能实现区域填充:
import matplotlib.pyplot as plt from scipy.stats import gaussian_kde import numpy as np # 替换为你的真实数据 data = np.random.randint(0, 60, size=1000) # 绘制原始直方图(可选,用于对比) plt.hist( data, range=[0, 60], bins=60, density=True, label="In bulk", histtype="stepfilled", alpha=0.3, ) # 计算KDE得到平滑曲线 kde = gaussian_kde(data) xvals = np.linspace(0, 60, 200) # 更密集的x轴点保证平滑度 yvals = kde(xvals) # 绘制平滑曲线并填充下方区域 plt.plot(xvals, yvals, label="Smoothed PDF", color="orange") plt.fill_between(xvals, yvals, alpha=0.4, color="orange") plt.legend() plt.xlabel("Value") plt.ylabel("Density") plt.show()
2. 拟合最优分布曲线
用scipy.stats中的分布函数拟合数据参数,生成最优拟合曲线(以正态分布为例,可替换为其他分布):
from scipy.stats import norm # 拟合正态分布参数:均值loc、标准差scale loc, scale = norm.fit(data) # 生成拟合曲线的y值 fit_yvals = norm.pdf(xvals, loc=loc, scale=scale) # 绘制拟合曲线 plt.plot(xvals, fit_yvals, label=f"Fitted Normal (μ={loc:.2f}, σ={scale:.2f})", color="red", linestyle="--") plt.legend() plt.xlabel("Value") plt.ylabel("Density") plt.show()
3. 完整整合代码
将平滑PDF、填充区域和拟合曲线整合:
import matplotlib.pyplot as plt from scipy.stats import gaussian_kde, norm import numpy as np # 替换为你的真实数据 data = np.random.randint(0, 60, size=1000) # 绘制原始直方图 plt.hist( data, range=[0, 60], bins=60, density=True, label="In bulk", histtype="stepfilled", alpha=0.3, ) # 生成平滑KDE曲线并填充 kde = gaussian_kde(data) xvals = np.linspace(0, 60, 200) yvals = kde(xvals) plt.plot(xvals, yvals, label="Smoothed PDF", color="orange") plt.fill_between(xvals, yvals, alpha=0.4, color="orange") # 拟合正态分布曲线 loc, scale = norm.fit(data) fit_yvals = norm.pdf(xvals, loc=loc, scale=scale) plt.plot(xvals, fit_yvals, label=f"Fitted Normal (μ={loc:.2f}, σ={scale:.2f})", color="red", linestyle="--") plt.legend() plt.xlabel("Value") plt.ylabel("Density") plt.title("Smoothed PDF with Fitted Curve") plt.show()
说明
- KDE的平滑程度可通过
gaussian_kde的bw_method参数调整,值越小曲线越平滑,越大越贴近原始数据 - 若尝试其他分布,只需替换
norm为scipy.stats中的对应分布(如gamma、expon等),调用其fit和pdf方法即可
内容的提问来源于stack exchange,提问作者Arka Bera
相关产品推荐
相关产品推荐

