RafaBitten
RafaBitten

Reputation: 21

How to format axis x date ('dd/mm/yyyy')?

I had searched for how to change the format of my axis x from 'Y-m-d' to 'd/m/Y' using pandas and matplotlib, but I couldn't find anything that works for me.

So, here is my code:

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) 

I got this error:

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()

Upvotes: 1

Views: 1731

Answers (1)

RafaBitten
RafaBitten

Reputation: 21

I solved this with help of ImportanceOfBeingErnest, using xticklabels

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

Upvotes: 1

Related Questions