【问题标题】:Plot outliers using matplotlib and seaborn使用 matplotlib 和 seaborn 绘制异常值
【发布时间】:2021-03-04 04:41:39
【问题描述】:

我对某购物中心的一些入口传感器数据执行了异常值检测。我想为每个入口创建一个图并突出显示异常值(在数据框中的 outlier 列中标记为 True)。

这是两个入口和六天时间跨度的数据的小sn-p:

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

df = pd.DataFrame({"date": [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6],
                   "mall": ["Mall1", "Mall1", "Mall1", "Mall1", "Mall1", "Mall1", "Mall1", "Mall1", "Mall1", "Mall1", "Mall1", "Mall1"],
                   "entrance": ["West", "West","West","West","West", "West", "East", "East", "East", "East", "East", "East"],
                   "in": [132, 140, 163, 142, 133, 150, 240, 250, 233, 234, 2000, 222],
                   "outlier": [False, False, False, False, False, False, False, False, False, False, True, False]})

为了创建几个图(完整数据有二十个入口),我在seaborn中遇到了lmplot。

sns.set_theme(style="darkgrid")
for i, group in df.groupby('entrance'):
    sns.lmplot(x="date", y="in", data=group, fit_reg=False, hue = "entrance")
    #pseudo code
    #for the rows that have an outlier (outlier = True) create a red dot for that observation
plt.show()

我想在这里完成两件事:

  1. 线图而不是散点图。我没有成功使用 sns.lineplot 为每个入口创建单独的图,因为 lmplot 似乎更适合于此。
  2. 对于每个入口图,我想显示哪些观察值是异常值,最好显示为红点。我尝试在绘图尝试中编写一些伪代码。

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:
    • seaborn.lmplotFacetgrid,我认为在这种情况下更难使用。
    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    
    for i, group in df.groupby(['entrance']):
    
        # plot all the values as a lineplot
        sns.lineplot(x="date", y="in", data=group)
        
        # select the data when outlier is True and plot it
        data_t = group[group.outlier == True]
        sns.scatterplot(x="date", y="in", data=data_t, c=['r'])
    
        # add a title using the value from the groupby
        plt.title(f'Entrance: {i}')
        
        # show the plot here, not outside the loop
        plt.show()
    

    备用选项

    • 此选项将允许设置图形的列数和行数
    import math
    
    # specify the number of columns to plot
    ncols = 2
    
    # determine the number of rows, even if there's an odd number of unique entrances
    nrows = math.ceil(len(df.entrance.unique()) / ncols)
    
    fig, axes = plt.subplots(ncols=ncols, nrows=nrows, figsize=(16, 16))
    
    # extract the axes into an nx1 array, which is easier to index with idx.
    axes = axes.ravel()
    
    for idx, (i, group) in enumerate(df.groupby(['entrance'])):
    
        # plot all the values as a lineplot
        sns.lineplot(x="date", y="in", data=group, ax=axes[idx])
        
        # select the data when outlier is True and plot it
        data_t = group[group.outlier == True]
        sns.scatterplot(x="date", y="in", data=data_t, c=['r'], ax=axes[idx])
        axes[idx].set_title(f'Entrance: {i}')
    

    【讨论】:

    • @torkestativ import matplotlib.pyplot as plt
    • 啊,谢谢!我错误地将其导入为“import matplotlib as plt”
    • @torkestativ 我添加了一个替代选项,它允许您指定图形的行和列,而不是一个接一个地绘制。
    • 这对于完整数据集产生的大量绘图非常有用。我的手指因滚动而感到疲倦。感谢您抽出宝贵的时间:)
    • @torkestativ 不客气。很高兴这对你有用。
    猜你喜欢
    • 2020-08-31
    • 2018-11-23
    • 1970-01-01
    • 2019-05-21
    • 2021-07-07
    • 2017-11-24
    • 2019-10-21
    • 2019-07-13
    • 1970-01-01
    相关资源
    最近更新 更多