如何在 seaborn ecdf 图上的 axhline 的交点上找到 x 值?

how to find x value on a intersection point of axhline on seaborn ecdf plot?

我有这样的 ecdf 图:

penguins = sns.load_dataset("penguins")
fig, ax = plt.subplots(figsize = (10,8))
sns.ecdfplot(data=penguins, x="bill_length_mm", hue="species")
ax.axhline(.25, linestyle = '--', color ='#cfcfcf', lw = 2, alpha = 0.75)

如何找到这条相交轴线上的 x 值?

您可以遍历生成的曲线 (ax.get_lines()),提取它们的坐标并搜索第一个大于所需 y 值的 y 值的索引。

下面是一些说明代码(注意 sns.ecdfplot() 应该得到 ax 作为参数):

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

penguins = sns.load_dataset("penguins")
fig, ax = plt.subplots(figsize=(10, 8))
sns.ecdfplot(data=penguins, x="bill_length_mm", hue="species", ax=ax)
y_special = 0.25
for line in ax.get_lines():
    x, y = line.get_data()
    ind = np.argwhere(y >= y_special)[0, 0]  # first index where y is larger than y_special
    # x[ind] is the desired x-value
    ax.text(x[ind], y_special, f' {x[ind]:.1f}', ha='left', va='top') # maybe color=line.get_color()
ax.axhline(y_special, linestyle='--', color='#cfcfcf', lw=2, alpha=0.75)
plt.show()

PS:您可以选择将这些 x 值添加到图例中:

for line, legend_text in zip(ax.get_lines(), ax.legend_.get_texts()):
    x, y = line.get_data()
    ind = np.argwhere(y >= y_special)[0, 0]
    legend_text.set_text(f'{x[ind]:5.2f} {legend_text.get_text()}')

在这种情况下,最好使用 pandas 提供的计算工具,而不是试图从视觉表示中支持定量值。

如果您想要每个物种对应于 .25 分位数的值,您应该这样做:

penguins.groupby("species")["bill_length_mm"].quantile(.25)

哪个returns

species
Adelie       36.75
Chinstrap    46.35
Gentoo       45.30
Name: bill_length_mm, dtype: float64