【问题标题】:Plot hist with date index on x axis在 x 轴上绘制带有日期索引的历史记录
【发布时间】:2020-04-09 18:45:43
【问题描述】:

我有以下数据:

            num_incidents
date                     
2014-01-01            208
2014-01-02            112
...                   ...
2018-03-30             67
2018-03-31             77

如果我尝试使用默认直方图方法绘制它,我会得到以下输出:

daily_incidents_df.hist()
plt.show()

虽然这很有用,但我还想绘制如下内容:

【问题讨论】:

    标签: python pandas matplotlib histogram


    【解决方案1】:

    假设源DataFrame包含:

                num_incidents
    date                     
    2014-01-01            208
    2014-01-02            112
    2015-02-02            100
    2015-03-02            130
    2016-02-02            130
    2016-03-02            130
    2011-02-02            170
    2011-03-02            130
    2018-03-30             67
    2018-03-31             77
    

    计算年度总数:

    s = df.num_incidents.groupby(df.index.year).sum()
    

    然后绘制你的图片,运行:

    ax = s.plot.bar(rot=0, width=0.9)
    ax.set_xlabel('Year', fontsize=16)
    ax.set_ylabel('Incidents', fontsize=16);
    

    注意; 终止最后一条指令,以抑制 关于最后创建的绘图对象的附加显示。

    将 width 参数设置为略低于 1.0,以填充几乎所有空间 每年都有酒吧。 对于以上数据,我得到了以下图片:

    【讨论】:

      【解决方案2】:

      您可以创建一个年份列:

      df['Year'] = df['date'].dt.year
      df[['Year', 'num_incidents']].hist()
      

      【讨论】:

      • 这很接近,唯一的问题是它给出了一个带有一年中天数(365)的直方图,而不是事件数
      猜你喜欢
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      • 2011-08-02
      • 2015-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-06
      相关资源
      最近更新 更多