pyplot.text() 在没有 y 坐标位置的箱线图上

pyplot.text() on a boxplot without a y coordinate position

我正在尝试为只有 x-coordinate 值的一维箱线图的中值、离群值和四分位数创建标签。我想标记查询,url,以及中位数、四分位数和离群值的点击率。数据框如下所示:

URL Clicks CTR Query
website.com/1 20 0.06 query1
website.com/2 4 0.10 query2

我没有标签的箱线图:

我对上述情节的代码:

df_ = df[df.Clicks > 4 ]
sns.boxplot(x=df_['CTR'])
plt.xlabel("CTR")
plt.show()

到目前为止我得到的是值和异常值限制:

median = df_['CTR'].median()
ctr_q1 = df_.quantile(0.25)['CTR']
ctr_q3 = df_.quantile(0.75)['CTR']
outlier_lim = ctr_q3 + 1.5 * (ctr_q3 - ctr_q1)

我的问题是,在尝试添加文本时,我不确定要在 plt.text() 中放入什么,而没有在以下代码中定位的 y 值:

for i in df_["CTR"]:
    if i > outlier_lim:
        plt.text(x = i, y=????? s = "here")

如果我尝试为 y 设置任意值,例如 0 或 1,我会得到如下结果:

>>> for i in df_["CTR"]:
...     if i > outlier_lim:
...         plt.text(x = i, y = 0, s = "here")
... 
Text(0.6923076923076923, 0, 'here')
Text(0.47619047619047616, 0, 'here')
Text(0.5333333333333333, 0, 'here')
Text(0.4583333333333333, 0, 'here')
Text(0.5, 0, 'here')
Text(0.5, 0, 'here')
Text(0.5, 0, 'here')
Text(0.5384615384615384, 0, 'here')
Text(0.5833333333333334, 0, 'here')
Text(0.5, 0, 'here')
Text(0.5, 0, 'here')
Text(0.55, 0, 'here')
Text(0.6153846153846154, 0, 'here')
>>> plt.xlabel("CTR")
Text(0.5, 0, 'CTR')
>>> plt.show()

我看到的大多数相关帖子都使用需要 y 参数的 seaborn 或 matplotlib 函数。当 y 不存在时,有人有解决方案吗?

谢谢!

中心线的 y 位置在 y=0。该框从 y=-0.4 变为 y=0.4,但请注意 y 轴是相反的(负值在顶部)。 y 值确实存在,但会自动隐藏以避免分散注意力。

下面是一些示例代码(请注意,seaborn 会自动将 xlabel 设置为列的名称):

from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator, ScalarFormatter
import seaborn as sns
import numpy as np
import pandas as pd

np.random.seed(2021)
df_ = pd.DataFrame({'CTR': np.random.geometric(0.5, size=80) / 100})
ax = sns.boxplot(x=df_['CTR'])

# show the ytick positions, as a reference
ax.yaxis.set_major_locator(MultipleLocator(0.1))
ax.yaxis.set_major_formatter(ScalarFormatter())

median = df_['CTR'].median()
ctr_q1 = df_.quantile(0.25)['CTR']
ctr_q3 = df_.quantile(0.75)['CTR']
outlier_lim = ctr_q3 + 1.5 * (ctr_q3 - ctr_q1)
for i in df_["CTR"]:
    if i > outlier_lim:
        ax.text(x=i, y=0.01, s="here", ha='center', va='top')
plt.show()