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

Jay*_*bir 2 python matplotlib ecdf seaborn

我有一个像这样的 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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

Joh*_*anC 5

您可以循环遍历生成的曲线 ( 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()
Run Code Online (Sandbox Code Playgroud)

示例图

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()}')
Run Code Online (Sandbox Code Playgroud)