首页 > 解决方案 > 使用 fit=stats.norm 在 sns.distplot 中将 y 轴更改为百分比

问题描述

我正在绘制一系列高斯分布,据我了解,y 轴是密度而不是概率。有没有办法将其更改为百分比或概率?我的代码如下:

import seaborn as sns
import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import norm    

x = np.random.normal(size=500) * 0.1
ax = plt.figure()
sns.distplot(x, bins=15, kde =False, fit=norm, color='lightseagreen', fit_kws={"color":"lightseagreen"}, hist_kws=dict(alpha=0.7))

拟合的高斯分布

标签: pythonseaborn

解决方案


您可以尝试手动定义箱,然后绘制直方图,这给你计数:

import seaborn as sns
import numpy as np
from matplotlib import pyplot as plt
from scipy.stats import norm 

x = np.random.normal(size=500) * 0.1

fig, ax = plt.subplots()

nbins = 20
xlen = np.linspace(-0.4,0.4,nbins)
binwidth = xlen[1] - xlen[0]
sns.distplot(x, bins=xlen, kde =False, color='lightseagreen', 
             fit_kws={"color":"lightseagreen"}, hist_kws=dict(alpha=0.7),ax=ax)

在此处输入图像描述

然后拟合正态分布,使用 cdf 的差值获得这些 bin 内的概率,然后按比例缩小 y-ticks:

mu, std = norm.fit(x)
p = np.diff(norm.cdf((xlen-mu)/std))
ax.plot(xlen[:(len(xlen)-1)]+binwidth/2,p*len(x),color='lightseagreen')
ax.set_yticklabels(ax.get_yticks()/len(x))

在此处输入图像描述


推荐阅读