我正在嘗試為只有 x 坐標值的一維箱線圖的中位數、例外值和四分位數創建標簽。我想為中位數、四分位數和例外值標記查詢、網址和點擊率。這是資料框的樣子:
| 網址 | 點擊次數 | 點擊率 | 詢問 |
|---|---|---|---|
| 網站.com/1 | 20 | 0.06 | 查詢1 |
| 網站.com/2 | 4 | 0.10 | 查詢2 |
我的沒有標簽的箱線圖:

我上面情節的代碼:
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 不存在時,有人有解決方案嗎?
謝謝!
uj5u.com熱心網友回復:
中心線的 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()

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/337710.html
標籤:Python matplotlib 海生 箱形图
