如何格式化轴x日期(' dd / mm / yyyy')?

时间:2018-01-19 15:37:42

标签: python pandas date matplotlib plot

我曾搜索过如何更改轴x的格式来自' Y-m-d'到' d / m / Y'使用pandasmatplotlib,但我无法找到适合我的任何内容。

所以,这是我的代码:

import matplotlib.dates as mdates
df_w = df['week'] == dt.datetime.strptime('2016-03-13','%Y-%m-%d')
ax = df[df_w].plot(kind='bar',x='week');
_fmt = mdates.DateFormatter('%d/%m/%Y')
ax.xaxis.set_major_formatter(_fmt) 

我收到了这个错误:

ValueError: DateFormatter found a value of x=0, which is an illegal
date.  This usually occurs because you have not informed the axis that
it is plotting dates, e.g., with ax.xaxis_date()

1 个答案:

答案 0 :(得分:1)

我使用xticklabels

ImportanceOfBeingErnest的帮助下解决了这个问题
df_w = df['week'] == dt.datetime.strptime('2016-03-13','%Y-%m-%d')
ax = df[df_w].plot(kind='bar',x='week');
ax.set_xlabel("Week");
new_label = []
for i in ax.get_xticklabels():
    date = dt.datetime.strptime(i.get_text(), '%Y-%m-%d %H:%M:%S')
    new_label.append(date.strftime("%d/%m/%Y"))

ax.set_xticklabels(new_label);

output