代码之家  ›  专栏  ›  技术社区  ›  Nicolaesse

带日期时间索引的数据帧,如何每年绘制一个图?

  •  0
  • Nicolaesse  · 技术社区  · 6 年前

    我有一个名为 df 具有 datetimeIndex 一个月的第一天和一个名为 Val 一些数值。

    df.head()
    
    
    +------------+-----+
    |            | Val |
    +------------+-----+
    | DateTime   |     |
    | 2011-10-01 |  11 |
    | 2011-11-01 |  85 |
    | 2011-12-01 |  12 |
    | 2012-01-01 |  91 |
    | 2012-02-01 |  44 |
    +------------+-----+
    

    数据框包含2010年至2017年期间每个月的一行。我的目标是在同一图表中绘制每一行代表一年的所有值,在X轴上,我有月份(月份或01并不重要),在y轴上的数量是 瓦尔 .

    我的第一个想法是 df.groupby(df.index.year)['Val'].agg('sum').unstack() 但这会产生一个错误。 属性错误:

    “Int64Index”对象没有“remove\u unused\u levels”属性

    然后我写了下面的代码,它可以工作,但有一些问题:

    • 我必须列出所有的年份;
    • 我得列出这条线的所有颜色
    • 很难创造一个传奇

    .

    fig, ax1 = plt.subplots(figsize=(20,7))
    months = df['2018'].index
    ax1.set_xlabel('months')
    ax1.set_ylabel('Sales')
    ax1.plot(months, df['2018'], color='navy')
    ax1.plot(months, df['2017'], color='blue')
    ax1.plot(months, df['2016'], color='lightblue')
    ax1.plot(months, df['2015'], color='lime')
    plt.grid()
    
    fig.tight_layout()
    plt.title('Sales per year', loc='center')
    
    plt.show()
    

    有没有更聪明的方法来生成情节?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Sheldore    6 年前

    因为您没有以可复制格式提供数据帧,所以我无法生成任何图形。不过,你还是可以试试下面的方法。可能还有其他方法 groupby 在数据帧上

    start = 2015
    end = 2018
    years = map(str, range(start, end+1))
    colors = ['lime', 'lightblue', 'blue', 'navy']
    
    for year, c in zip(years, colors):
        ax1.plot(months, df[year], color=c)
    
    plt.grid()
    fig.tight_layout()