a 的 y 轴histplot
with stat="probability"
对应于某个值属于某个柱的概率。的价值0.23
对于最高的条形,意味着鳍状肢长度介于两者之间的概率约为 23%189.7
and 195.6
毫米(即特定垃圾箱的边缘)。请注意,默认情况下,遇到的最小值和最大值之间分布有 10 个 bin。
a 的 y 轴kdeplot
类似于概率密度函数 https://en.wikipedia.org/wiki/Probability_density_function。曲线的高度与某个值位于宽度区间内的近似概率成正比1
相应的 x 值。值为0.031
for x=191
意味着有大约概率3.1 %
长度介于190.5
and 191.5
.
现在,直接获取a旁边的概率值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}')
另一种选择可能是画一个histplot
with kde=True
,并删除生成的条形。为了便于解释,abinwidth
应设置。和binwidth=1
你会得到与密度图相同的 y 轴。 (kde_kws={'cut': 3})
让 kde 平滑地接近零,默认 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()