My *_*ork 6 python histogram seaborn
我有一个关于seaborn的问题kdeplot。可以histplot设置他们想要的统计数据kde(计数、频率、密度、概率),如果与参数一起使用,它也适用于kdeplot. kdeplot但是,如果我只想使用概率进行 kde 图估计,我还没有找到如何直接更改它的方法。histplot或者,如果可以关闭酒吧,应该会得到相同的结果,但我也没有发现。那么如何才能做到这一点呢?
举一些直观的例子,我只想有红色曲线,即。要么将参数传递给kdeplotuse 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()
Run Code Online (Sandbox Code Playgroud)
多谢。
histplota的y 轴stat="probability"对应于某个值属于某个柱的概率。最高条的值0.23意味着鳍板长度介于189.7和195.6mm 之间(即特定箱的边缘)的概率约为 23%。请注意,默认情况下,遇到的最小值和最大值之间分布有 10 个 bin。
a 的 y 轴kdeplot类似于概率密度函数。1曲线的高度与某个值位于相应 x 值的宽度范围内的近似概率成正比。0.031for的值表示长度介于和 之间x=191的概率约为。3.1 %190.5191.5
现在,要直接获取 a 旁边的概率值kdeplot,首先需要选择 bin 宽度。然后,y 值可以除以该 bin,以对应于该宽度的 bin 内的 x 值。提供PercentageFormatter了一种使用 来设置此类对应关系的方法ax.yaxis.set_major_formatter(PercentFormatter(1/binwidth))。
下面的代码说明了 binwidth 为 的示例5 mm,以及 a 如何histplot匹配 a 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()
Run Code Online (Sandbox Code Playgroud)
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}')
Run Code Online (Sandbox Code Playgroud)
另一种选择可能是用 绘制histplot,kde=True并删除生成的条形。为了便于解释,binwidth应该设置 a。这样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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12058 次 |
| 最近记录: |