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

问题描述 投票:1回答:1

我正在尝试使用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()
python-3.x seaborn gaussian curve bell-curve
1个回答
0
投票

seaborn中没有任何选项可以还原为计数,因为一旦打开kde,norm_hist选项就是False。要获得接近计数的东西,您需要首先定义箱宽度(sns.displot为您完成),然后使用gaussian_kde执行密度。这些值是密度,您可以通过将密度值乘以binwidth和观测值数量来进行转换,例如counts_i = n * dens_i * binwidth

我们可以检查此:

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()

enter image description here

左侧的第一张图带有计数的直方图,右侧的第二张图带有计数的密度图。

© www.soinside.com 2019 - 2024. All rights reserved.