使用fit = stats.norm将y轴更改为sns.distplot中的百分比

时间:2020-05-26 16:03:58

标签: python seaborn

我正在绘制一系列高斯分布,据我了解,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))

Gaussian distribution with fit

1 个答案:

答案 0 :(得分:0)

您可以尝试手动定义垃圾箱,然后绘制直方图,从而获得计数:

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)

enter image description here

然后拟合正态分布,使用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))

enter image description here