簡體   English   中英

Seaborn kde plot 繪制概率而不是密度(沒有條形的直方圖)

[英]Seaborn kde plot plotting probabilities instead of density (histplot without bars)

我有一個關於 seaborn kdeplot的問題。 histplot中,可以設置他們想要的統計數據(計數、頻率、密度、概率),如果與kde參數一起使用,它也適用於kdeplot 但是,如果我只想用概率估計 kde plot,我還沒有找到如何直接在kdeplot中更改它的方法。 或者,如果可以關閉條形圖,則應該來自histplot的相同結果,我也沒有找到。 那么如何做到這一點呢?

舉一些直觀的例子,我想只有紅色曲線,即。 要么將參數傳遞給kdeplot以使用probabilities ,要么從histplot中刪除條形:

import seaborn

penguins = sns.load_dataset("penguins")
sns.histplot(data=penguins, x="flipper_length_mm", kde=True, stat="probability", color="r", label="probabilities")
sns.kdeplot(data=penguins, x="flipper_length_mm", color="k", label="kde density")
plt.legend()

im1 - kde 和 hist 圖

非常感謝。

stat="probability"histplot的 y 軸對應於某個值屬於某個條形的概率。 最高條的值為0.23 ,意味着鰭板長度介於189.7195.6毫米之間(即該特定箱的邊緣)的概率約為 23%。 請注意,默認情況下,10 個 bin 分布在遇到的最小值和最大值之間。

kdeplot的 y 軸類似於概率密度 function 曲線的高度與某個值在相應 x 值的寬度為1的 bin 內的近似概率成比例。 x=191的值為0.031表示長度介於190.5191.5之間的概率約為3.1 %

現在,要直接獲取kdeplot旁邊的概率值,首先需要選擇 bin 寬度。 然后 y 值可以除以該 bin 以對應於在該寬度的 bin 內的 x 值。 PercentageFormatter提供了一種設置這種對應關系的方法,使用ax.yaxis.set_major_formatter(PercentFormatter(1/binwidth))

下面的代碼說明了一個 binwidth 為5 mm的示例,以及histplot如何匹配kdeplot

import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import PercentFormatter

fig, ax1 = plt.subplots()
penguins = sns.load_dataset("penguins")
binwidth = 5
sns.histplot(data=penguins, x="flipper_length_mm", kde=True, stat="probability", color="r", label="Probabilities",
             binwidth=binwidth, ax=ax1)
ax2 = ax1.twinx()
sns.kdeplot(data=penguins, x="flipper_length_mm", color="k", label="kde density", ls=':', lw=5, ax=ax2)
ax2.set_ylim(0, ax1.get_ylim()[1] / binwidth)  # similir limits on the y-axis to align the plots
ax2.yaxis.set_major_formatter(PercentFormatter(1 / binwidth))  # show axis such that 1/binwidth corresponds to 100%
ax2.set_ylabel(f'Probability for a bin width of {binwidth}')
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')
plt.show()

示例圖

PS:為了只顯示概率的kdeplot ,代碼可以是:

binwidth = 5
ax = sns.kdeplot(data=penguins, x="flipper_length_mm")
ax.yaxis.set_major_formatter(PercentFormatter(1 / binwidth))  # show axis such that 1/binwidth corresponds to 100%
ax.set_ylabel(f'Probability for a bin width of {binwidth}')

另一種選擇是使用kde=True繪制一個histplot ,並刪除生成的條形圖。 為了便於解釋,應該設置一個binwidth 使用binwidth=1 ,您將獲得與密度 plot 相同的 y 軸。 ( kde_kws={'cut': 3})讓 kde 平滑 go 到零左右,默認 kde 曲線以數據的最小值和最大值截斷)。

ax = sns.histplot(data=penguins, x="flipper_length_mm", binwidth=1, kde=True, stat='probability', kde_kws={'cut': 3})
ax.containers[0].remove() # remove the bars
ax.relim() # the axis limits need to be recalculated without the bars
ax.autoscale_view()

暫無
暫無

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

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