【问题标题】:plot a seaborn boxplot with month as x-axes with a daily dataset使用每日数据集绘制以月份为 x 轴的 seaborn 箱线图
【发布时间】:2018-08-30 12:26:12
【问题描述】:

我有一个这样的数据集:

>>> print(ds.head())

         date     sum
  0  2013-08-31  19.000
  1  2013-09-01  37.000
  2  2013-09-02  10.750
  3  2013-09-03  21.500
  4  2013-09-04  44.125

>>> print(ds.tail())


            date      sum
    1742  2018-08-24  129.875
    1743  2018-08-25  196.375
    1744  2018-08-26  247.000
    1745  2018-08-27  104.125
    1746  2018-08-28  149.250

数据集包含大约 1700 行每日数据。 我想绘制一个箱线图,以便查看每月值。 像这样的东西

我需要 X 轴上的月份,例如 JAN/FEB/MAR 等。

如果我有每日数据集,我找不到任何可行的解决方案来实现这一点。我想我必须先做数据准备并对每月的值进行分组? 或者我怎样才能以一种简单快捷的方式进行编程?

【问题讨论】:

    标签: python seaborn boxplot


    【解决方案1】:

    您可以使用dt.strftime('%b') 元素并按如下方式创建月份列:

    df=pd.DataFrame(np.random.randint(50,1000,365).reshape(-1,1),
                    index=pd.date_range('2018-01-01','2018-12-31',freq='D'),
                    columns=['sum'])
    df.reset_index(inplace=True)
    df.columns = ['Date','sum']
    df.head()
    
              Date  sum
    0   2018-01-01  984
    1   2018-01-02  582
    2   2018-01-03  967
    3   2018-01-04  503
    4   2018-01-05  330
    
    df['month'] = df['Date'].dt.strftime('%b')
    

    使用seaborn.boxplot 并传递x='month'y='sum'data=df 作为参数。您将获得所需的箱线图。

    fig, ax = plt.subplots()
    fig.set_size_inches((12,4))
    sns.boxplot(x='month',y='sum',data=df,ax=ax)
    plt.show()
    

    绘图颜色等参数未设置为OP的显示绘图。

    【讨论】:

      【解决方案2】:

      假设您的 DataFrame df 包含“日期”和“总和”两列,我们需要在“日期”字段中对其进行排序,以使行按正确的顺序排列,否则我们可以看到月份顺序错误。然后我们需要创建一个包含每个日期月份名称的支持列。就是这样,我们准备好剧情了。

      代码如下:

      import pandas as pd
      import seaborn as sns
      
      # just an example...
      df = pd.DataFrame([["2013-08-31", 19], ["2013-09-01", 37], ["2013-09-02", 10.75]], columns=["date", "sum"])
      
      # sort the rows by date
      df.sort_values(by="date", inplace=True)
      
      # create a support series with the name of the month of each row
      month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
      months = df["date"].apply(lambda date: month_names[int(date.split("-")[1])-1])
      
      # plot it
      sns.boxplot(months, df["sum"])
      

      希望对你有帮助。

      【讨论】:

        【解决方案3】:

        您可以从日期时间使用函数strftime

        这是一个例子:

        from datetime import date
        import random
        import pandas as pd
        from seaborn import boxplot
        
        dates = [date.today()]*10
        dataSum = [random.randint(1,100) for x in range(10)] 
        
        d = {'date': dates, 'sum':dataSum}
        df = pd.DataFrame(data = d)
        
        dateData =  [x.strftime('%B') for x in df['date']]
        boxplot(dateData, df['sum'])
        

        Resulting Plot

        【讨论】:

          猜你喜欢
          • 2021-09-29
          • 2020-10-16
          • 1970-01-01
          • 2021-12-29
          • 1970-01-01
          • 1970-01-01
          • 2020-12-21
          • 2021-06-24
          • 2023-04-10
          相关资源
          最近更新 更多