Boxplot:异常值标签 Python

KB2*_*B23 6 python matplotlib outliers boxplot seaborn

我正在使用 seaborn 包制作时间序列箱线图,但我无法在异常值上贴上标签。

我的数据是一个 3 列的数据框:[Month , Id , Value]我们可以像这样伪造:

### Sample Data ###
Month = numpy.repeat(numpy.arange(1,11),10)
Id = numpy.arange(1,101)
Value = numpy.random.randn(100)

### As a pandas DataFrame ###
Ts = pandas.DataFrame({'Value' : Value,'Month':Month, 'Id': Id})

### Time series boxplot ###
ax = seaborn.boxplot(x="Month",y="Value",data=Ts)
Run Code Online (Sandbox Code Playgroud)

我每个月都有一个箱线图,我试图将其Id作为图中三个异常值的标签:
1

Zep*_*hyr 3

首先,您需要检测Id数据框中哪些是异常值,您可以使用以下命令:

outliers_df = pd.DataFrame(columns = ['Value', 'Month', 'Id'])
for month in Ts['Month'].unique():
        outliers = [y for stat in boxplot_stats(Ts[Ts['Month'] == month]['Value']) for y in stat['fliers']]
        if outliers != []:
                for outlier in outliers:
                        outliers_df = outliers_df.append(Ts[(Ts['Month'] == month) & (Ts['Value'] == outlier)])
Run Code Online (Sandbox Code Playgroud)

它创建一个与原始数据框类似的数据框,仅包含异常值。
然后你可以Id用这个注释你的情节:

for row in outliers_df.iterrows():
        ax.annotate(row[1]['Id'], xy=(row[1]['Month'] - 1, row[1]['Value']), xytext=(2,2), textcoords='offset points', fontsize=14)
Run Code Online (Sandbox Code Playgroud)

完整代码:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.cbook import boxplot_stats
sns.set_style('darkgrid')

Month = np.repeat(np.arange(1,11),10)
Id = np.arange(1,101)
Value = np.random.randn(100)

Ts = pd.DataFrame({'Value' : Value,'Month':Month, 'Id': Id})

fig, ax = plt.subplots()
sns.boxplot(ax=ax, x="Month",y="Value",data=Ts)

outliers_df = pd.DataFrame(columns = ['Value', 'Month', 'Id'])
for month in Ts['Month'].unique():
        outliers = [y for stat in boxplot_stats(Ts[Ts['Month'] == month]['Value']) for y in stat['fliers']]
        if outliers != []:
                for outlier in outliers:
                        outliers_df = outliers_df.append(Ts[(Ts['Month'] == month) & (Ts['Value'] == outlier)])

for row in outliers_df.iterrows():
        ax.annotate(row[1]['Id'], xy=(row[1]['Month'] - 1, row[1]['Value']), xytext=(2,2), textcoords='offset points', fontsize=14)

plt.show()
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述