【问题标题】:pandas: How to format timestamp axis labels nicely in df.plt()?pandas:如何在 df.plt() 中很好地格式化时间戳轴标签?
【发布时间】:2016-10-12 15:49:48
【问题描述】:

我有一个如下所示的数据集:

          prod_code      month  items      cost
0  040201060AAAIAI 2016-05-01      5    572.20 
1  040201060AAAKAK 2016-05-01    164  14805.19  
2  040201060AAALAL 2016-05-01  13465  14486.07   

执行df.dtypes 表明month 列是datetime64[ns] 类型。

我现在正在尝试绘制特定产品的每月成本:

df[df.bnf_code=='040201060AAAIAI'][['month', 'cost']].plot()
plt.show()

这可行,但 x 轴不是我所期望的时间戳:

如何使用月份和年份标签很好地格式化 x 轴标签?

更新:我也试过这个,得到一个条形图,它在 x 轴上输出时间戳,但格式很长,很笨拙:

df[df.bnf_code=='040201060AAAIAI'].plot.bar(x='month', y='cost', title='Spending on 040201060AAAIAI')

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    如果将日期设置为索引,则应正确标记 x 轴:

    df[df.bnf_code=='040201060AAAIAI'][['month', 'cost']].set_index('month').plot()
    

    我只是在您的代码中添加了set_index

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-28
      • 2019-02-01
      • 2017-09-27
      • 2011-01-11
      • 2012-09-04
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      相关资源
      最近更新 更多