从分组的熊猫系列创建晶须图

时间:2020-10-23 13:14:11

标签: python pandas pandas-groupby

我有一个以5分钟为时间戳的时间间隔到达的值的数据集,我将其可视化为一天中的小时,就像这样hours_group

我想将其转换为晶须/盒子图,以获取更多信息。但是,此图的matplotlibseabornpandas的实现都希望使用原始数据数组来自己计算图的内容。

是否可以通过预先计算/分组的平均值,中位数,std和四分位数创建晶须图?我想避免使用效率相对较低的分组算法来重新发明轮子,从而为此目的构建每日数据集。


这是一些代码,用于产生玩具数据和当前情节的版本。

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

# some toy data in a 15-day range
data = [1.5+np.sin(x)*5 for x in np.arange(0, 403.3, .1)]
s = pd.Series(data=data, index=pd.date_range('2019-01-01', '2019-01-15', freq='5min'))

s.groupby(s.index.hour).mean().plot(kind='bar')
plt.show()

添加到@Quang Hoang的解决方案中:您也可以使用hlines()显示中位数:

axis.bar(data.index, data['q75'] - data['q25'], bottom=data['q25'], width=wd)
axis.hlines(y=data['median'], xmin=data.index-wd/2, xmax=data.index+wd/2, color='black', linewidth=1)

1 个答案:

答案 0 :(得分:1)

我认为没有任何意义。但是,您可以使用两个plot命令相当简单地创建晶须图:

# precomputed data:
data = (s.groupby(s.index.hour)
         .agg(['mean','std','median',
               lambda x: x.quantile(.25),
               lambda x: x.quantile(.75)])
       )
data.columns = ['mean','std','median','q25','q75']


# plot the whiskers with `errorbar` from `mean` and `std`
fig, ax = plt.subplots(figsize=(12,6))
ax.errorbar(data.index,data['mean'], 
            yerr=data['std']*1.96, 
            linestyle='none',
            capsize=5
            )

 # plot the boxes with `bar` at bottoms from quantiles
ax.bar(data.index, data['q75']-data['q25'], bottom=data['q25'])

输出:

enter image description here