【问题标题】:Splitting groupby results for subplots拆分子图的 groupby 结果
【发布时间】:2020-07-14 11:02:16
【问题描述】:

我有一个数据框,stock_data.head():

       date     open    high    low     close    volume    Name
0   2013-02-08  15.07   15.12   14.63   14.75   8407500     AAL
1   2013-02-11  14.89   15.01   14.26   14.46   8882000     AAL
2   2013-02-12  14.45   14.51   14.10   14.27   8126000     AAL
3   2013-02-13  14.30   14.94   14.25   14.66   10259500    AAL
4   2013-02-14  14.94   14.96   13.16   13.99   31879900    AAL

下面我有一个代码,用于从我的数据框中生成 groupby 命令:

avg_permonth = stock_data.set_index('date').groupby(pd.Grouper(freq='M'))
avg_permonth['volume'].mean()


date
2013-02-28    5.261789e+06
2013-03-31    4.825485e+06
2013-04-30    4.990292e+06
2013-05-31    4.836257e+06
2013-06-30    5.145598e+06
                  ...     
2017-10-31    3.903486e+06
2017-11-30    4.133801e+06
2017-12-31    3.919748e+06
2018-01-31    4.486669e+06
2018-02-28    6.249305e+06
Freq: M, Name: volume, Length: 61, dtype: float64

我的问题是,如何按年份拆分这些结果,然后创建 date vs volume 的子图? (我必须先reset_index() 还是我可以将index 绘制为x axis?)我希望从2013-02 到2018-02 的5 个subplots。

我尝试了这个this SO post,但没有给出我想要的结果 - 它是 5 个子图,但 x axis 是从 2013 年到 2018 年的每个图,并且都有相同的图。

我希望第一个子图上的 x axis 是从 2013 年的第一个日期值到 2013 年的最后一个日期值,2014 年的第二个图等等。

【问题讨论】:

    标签: python pandas matplotlib pandas-groupby


    【解决方案1】:

    你可以这样做:

    import matplotlib.pyplot as plt
    
    # dummy values like your serie
    s = pd.Series(range(12*6), 
                  index=pd.date_range('2013-01-01', '2018-12-31', freq='M'), 
                  name='volume')
    
    # Create figure and axs for multiple Axes
    fig, axs = plt.subplots(3, 2, figsize=(12,12))
    
    # groupby year to plot each year un a subplot
    for i, (year, sg) in enumerate(s.groupby(s.index.year)):
        # plot each year in a subplot
        sg.plot(ax=axs[i//2, i%2]) # here you can add several parameters for colors and stuff
        # or axs[i//2, i%2].plot(sg.index, sg.values) would give the same result
    plt.show() 
    

    【讨论】:

    • 这与for 循环的顶行存在问题:AttributeError: Cannot access callable attribute 'groupby' of 'DataFrameGroupBy' objects, try using the 'apply' method 。为了换取您的s.groupby(s.index.year),我已将我的版本avg_permonth.groupby(avg_permonth.index.year)。我可以不做另一个groupby,因为它已经完成了吗? @Ben.T
    • @pragmaticlearner 我所谓的s 实际上与avg_permonth['volume'].mean() 的结构相同,因为我知道这是您想要绘制的,但是如果您的目标是绘制所有点,那么您可以将s.groupby(s.index.year) 替换为stock_data.set_index('date').groupby(pd.Grouper(freq='Y'))['volume'] 例如
    猜你喜欢
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多