簡體   English   中英

如何將 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 嚴格來說,當應用高斯 kernel 時,您將獲得其值取決於 binwidth 的密度,並且它可以是 >1

要獲得類似於計數的東西,您需要首先定義 bin 寬度(sns.displot 為您完成)並使用gaussian_kde執行密度。 這些值是密度,您可以通過將密度值乘以 binwidth 和觀察次數來進行轉換,例如counts_i = n * dens_i * binwidth

正如@mwaskom(見評論)所指出的那樣,僅顯示以y軸為計數的kde plot 可能不是最好的。

我們可以檢查一下:

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

在此處輸入圖像描述

左邊的第一個 plot 是帶有計數的直方圖,第二個 plot 是密度 plot 您擁有的“計數”密度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM