如何在箱线图中显示分位数的值

我设法在 x 轴上获得了 2 个类别的箱线图,在 y 轴上获得了一个连续变量。我只想在方框附近添加四分位数的值。

像这样:

enter image description here

stack overflow How to show the value of quantiles in a boxplot
原文答案
author avatar

接受的答案

Here is an example:

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

np.random.seed(0)
df = pd.DataFrame({'churn': np.random.choice(['No', 'Si'], size=1000),
                   'value': np.random.random(size=1000)})
box_width = 0.5
ax = sns.boxplot(data=df, x='churn', y='value', width=box_width)

i = 0
for name, group in df.groupby('churn'):
    Q1, Q3 = group['value'].quantile([0.25,0.75])
    for q in (Q1, Q3):
        x = i-box_width/2
        y = q
        ax.annotate('%.2f' % q, (x,y),
                    xytext=(x-0.1, y), textcoords='data',
                    arrowprops=dict(facecolor='black', shrink=0.05),
                    va='center', ha='right')
    
    i+=1

boxplot with arrows on quartiles


答案: