在Pandas图中控制datetime64 [ns]的表示

时间:2014-04-29 14:25:48

标签: python matplotlib pandas

说我有一个数据框,我做了一个箱图:

df.boxplot(column='value', by='date')

其中date是dtype datetime64[ns]的列。当我运行上面的图时,x轴显示刻度标签如下:

2014-02-24 00:00:00

非常罗嗦。我想展示像2014-02-24这样的东西(或者甚至更好,能够控制日期的格式化(例如“月 - 日”)

在Pandas有没有办法做到这一点?

供参考,我正在使用:

  • matplotlib:1.3.1
  • pandas:0.13.1
  • numpy:1.8.1

这是我的日期:

In <88>: df['date'].head()
Out<88>: 
0   2014-02-24
1   2014-02-24
2   2014-02-24
3   2014-02-24
4   2014-02-24
Name: date, dtype: datetime64[ns]

2 个答案:

答案 0 :(得分:2)

如果你有ax对象(例如来自ax = plt.add_subplot(1,1,1)ax = plt.gca()),那么你可以使用DateFormatter对象,如下面的代码所示,设置任何字符串格式你想要的。

字符串选项是strftime()给出的选项。

import matplotlib.dates as mdate

df.boxplot(...)

ax = plt.gca() # Gets the current axes

# String giving your date format as "MM-DD" e.g. "04-29"
date_fmt = '%m-%d'

date_formatter = mdate.DateFormatter(date_fmt)
ax.xaxis.set_major_formatter(date_formatter)

fig.autofmt_xdate() # Sets your dates slightly diagonal to fit better.

答案 1 :(得分:2)

也许你可以创建一个你想要的字符串值的新列:

df['date1']=df.date.apply(lambda x: x.strftime('%m-%y'))
ax=df.boxplot(column='value', by='date1')

enter image description here

相关问题