我有一个这样的数据集:
>>> 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 等。
如果我有每日数据集,我找不到任何可以实现此目的的可行解决方案。我想我必须首先进行数据准备并对每月的值进行分组? 或者我怎样才能以简单而简短的方式对此进行编程?
最佳答案
您可以使用 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()
关于python - 使用每日数据集绘制以月份为 x 轴的 seaborn 箱线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52097045/