【问题标题】:Boxplot : Outliers Labels Python箱线图:异常值标签 Python
【发布时间】:2017-03-21 02:11:40
【问题描述】:

我正在使用 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)

我每个月都有一个箱线图,我正在尝试将Id 作为三个异常值的标签放在此处:

【问题讨论】:

  • 欢迎来到 Stack Overflow。请花一些时间阅读如何编写Minimum, Complete and Verifiable Example。就目前而言,没有人知道您用于创建这些绘图的任何代码,因此我们无法为您提供适当的帮助。
  • 我相信这篇 stackoverflow.com/questions/35131798/tweaking-seaborn-boxplot 的帖子回答了您关于显示异常值的问题。
  • 感谢您的回答。我添加了一些关于我的问题的细节。 @jnic 我不是要显示异常值,而是要使用 Id 列显示异常值标签
  • 这里不使用 seaborn 是有意义的,因为它不能轻松访问底层功能。可以选择使用 matplotlib boxplot 作为here

标签: python matplotlib seaborn boxplot outliers


【解决方案1】:

首先,您需要检测数据框中的哪些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)])

创建一个数据框,类似于原始数据框,仅包含异常值。
然后你可以在你的情节上注释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)

完整代码:

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()

输出:

【讨论】:

    猜你喜欢
    • 2020-08-27
    • 2021-11-06
    • 1970-01-01
    • 2012-06-23
    • 2018-07-02
    • 1970-01-01
    • 2014-08-21
    • 2016-07-18
    • 2013-07-17
    相关资源
    最近更新 更多