代码之家  ›  专栏  ›  技术社区  ›  adhg veen

按日期(月和年)分组的matplotlib堆栈栏

  •  1
  • adhg veen  · 技术社区  · 6 年前

    dates = pd.DatetimeIndex(['2017-01-01 00:00:00', '2017-01-05 02:00:00','2017-03-01 02:00:00', '2018-01-01 03:00:00', '2018-01-21 04:00:00','2018-03-01 03:00:00', '2018-03-22 04:00:00'], dtype='datetime64[ns]')
    my_df = pd.DataFrame({"Date":dates,"Values":[5,1,2,4,6,3,5]})
    my_df
    

    enter image description here

    我的目标是 情节 一个堆栈条,这样x轴将有一个月\年,该条将显示一堆值。例如,2017年1月,我希望看到2种颜色,5和1的总和为6,以此类推。

    由于这是一个与group-by\u-date相关的问题,我想知道如何获得基于month-year的值列表,以便将它们正确地堆叠在一起,然后生成for循环:

    for each month_year:
         plt.bar(month_year, list_of_values_per_month_year, color='#whatever',)
    

    注意,不是每个月都有一个值,有些月有n个值。

    当然,除非我的方法从根本上说是复杂的,而且有一个更顺畅的方法。

    1 回复  |  直到 6 年前
        1
  •  1
  •   BENY    6 年前

    您需要首先创建 pivot 那就坐桌子吧 plot 堆叠条

    my_df.Date=my_df.Date.dt.strftime('%Y-%m')
    my_df['col']=my_df.groupby('Date').cumcount()
    my_df.pivot(index='Date',columns='col',values='Values').plot(kind='bar',stacked=True)
    

    enter image description here