使用每日数据集绘制以月份为 x 轴的 seaborn boxplot

ada*_*ama 1 python boxplot seaborn

我有一个这样的数据集:

>>> 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
Run Code Online (Sandbox Code Playgroud)

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

我需要像 JAN/FEB/MAR 等 x 轴上的月份。

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

San*_*apa 5

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

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')
Run Code Online (Sandbox Code Playgroud)

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

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

实际情节是这样的绘图颜色和其他参数未设置为 OP 的显示绘图。