python - 使用每日数据集绘制以月份为 x 轴的 seaborn 箱线图

标签 python seaborn boxplot

我有一个这样的数据集:

>>> 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 行每日数据。 我想绘制箱线图,以便查看每月值。 像这样的东西 monthly boxplot

我需要 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()

Actual Plot look like this绘图颜色和其他参数未设置为 OP 的显示绘图。

关于python - 使用每日数据集绘制以月份为 x 轴的 seaborn 箱线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52097045/

相关文章:

python - 请求(由于 SSL 模块不可用,由 SSLError ("Can' t 连接到 HTTPS URL 引起。”)PyCharm 请求网站中的错误

python - 如何更改seaborn lmplot中的标记填充样式?

python - 在 seaborn 情节中更改图例标题大小的优雅方法?

python - 在 seaborn 中绘制多个箱线图

python - matplotlib:多个箱形图的插入轴

python - 类的评估返回 false

python - 简单回归示例 pyBrain

python - 带有两个 y 尺度的 Seaborn despine (twinx)

r - R 中带有边缘箱线图的直方图

python - 如何停用 Hadoop 流中的输出?