如何将 seaborn.distplot() 中的 yticks 从标准化值更改为绝对值?

How to change yticks in the seaborn.distplot() from normalised values to absolute values?

我正在尝试使用 seaborn.displot() 方法创建高斯曲线(没有条形图)。不幸的是,我得到的是 y 轴上的标准化值而不是绝对值。我该如何解决这个问题?

这是我的代码:

height_mu = 165
height_sigma = 15
heights = np.random.normal(height_mu, height_sigma, size=10000)

plt.figure(figsize=(20, 5))
sns.distplot(heights, hist=False)
plt.axvline(165, color='red', label='Mean height (in cm)', linewidth=2)
plt.ylabel("Number of observations")
plt.legend()
plt.grid(which='major', axis='y', color='lightgrey')
plt.show()

seaborn 中没有恢复计数的选项,因为一旦打开 kde,norm_hist 选项就是 False。严格来说,当应用高斯核时,你得到的密度值取决于 binwidth 和 it can be >1.

要获得类似于计数的东西,您需要首先定义 bin 宽度(sns.displot 为您完成)并使用 gaussian_kde 执行密度。这些值是密度,您可以通过将密度值乘以 binwidth 和观测值数来进行转换,例如 counts_i = n * dens_i * binwidth

如@mwaskom 所述(见评论),仅显示以 y 轴为计数的 kde 图可能不是最好的。

我们可以检查一下:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

np.random.seed(999)
height_mu = 165
height_sigma = 15
heights = np.random.normal(height_mu, height_sigma, size=10000)
nbins = 50

fig,ax = plt.subplots(1,3,figsize=(10, 4))
sns.distplot(heights, hist=True,norm_hist=False,kde=False,bins=nbins,ax=ax[0])
sns.distplot(heights, hist=False,bins=nbins,ax=ax[1])
ax[1].axvline(165, color='red', label='Mean height (in cm)', linewidth=2)

from scipy.stats import gaussian_kde
dens = gaussian_kde(heights)
xlen,step = np.linspace(heights.min(),heights.max(),num=nbins,retstep=True)
ax[2].plot(xlen,len(heights)*dens(xlen)*step)
ax[2].axvline(165, color='red', label='Mean height (in cm)', linewidth=2)

fig.tight_layout()

左边的第一个图是带计数的直方图,第二个图是密度图,右边是 "counts" 的密度。