繁体   English   中英

如何在 x 轴上使用对数刻度将 pdf 叠加到 seaborn histplot

[英]How to overlay pdf to seaborn histplot with log scale on x axis

按照这个答案,我试图用我从 scipy.stats 获得的 pdf 绘制一个 seaborn histplot。 问题是绘制的 pdf 严重超出规模(示例如下):

from scipy import stats
import matplotlib.pyplot as plt
import seaborn as sns

params = (20, -1500, 8000)
sample = stats.invgauss.rvs(size=1000, *params)
fig, ax = plt.subplots()
sns.histplot(sample, log_scale=True, kde=False, stat='density')
x0, x1 = ax.get_xlim()
x_pdf = np.exp(np.linspace(np.log(x0),np.log(x1),500))
fitted_params = stats.invgauss.fit(sample)
y_pdf = stats.invgauss.pdf(x_pdf, *fitted_params)
y_cdf = stats.invgauss.cdf(x_pdf, *fitted_params)
ax.plot(x_pdf, y_pdf, 'r', lw=2)
plt.savefig('Pdf_check.png')

pdf 丢失

另一方面, cdf 打印良好并且与我的预期一致:

# same as above
ax.plot(x_pdf, y_cdf, 'r', lw=2)
plt.savefig('Cdf_check.png')

cdf 好的

我找到了解决方案。 很抱歉自我回答,但我认为将它写在这里对未来很有用。

使用log_scale=Truestat='density' ,seaborn 使用对数 bin 并重新调整 bin 高度,使积分为 1。因此,需要使用函数g代替pdf ,以便重新缩放 bin 上的积分与的PDF。 这给出了g(x) = f(x) * x * log(10)并且确实有效:

params = (20, -1500, 8000)
sample = stats.invgauss.rvs(size=1000, *params)
fig, ax = plt.subplots()
sns.histplot(sample, log_scale=True, kde=False, stat='density')
x0, x1 = ax.get_xlim()
x_pdf = np.exp(np.linspace(np.log(x0),np.log(x1),500))
fitted_params = stats.invgauss.fit(sample)
y_pdf = stats.invgauss.pdf(x_pdf, *fitted_params)
y_cdf = stats.invgauss.cdf(x_pdf, *fitted_params)
# rescaled pdf:
y_pdf_rescaled = y_pdf * x_pdf * np.log(10)
ax.plot(x_pdf, y_pdf_rescaled, 'r', lw=2)
plt.savefig('{}/Pdf_check.png'.format(out_dir))

重新缩放的pdf

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM