Sometimes, we want to change date format in Python Pandas bar plot, we use strftime.
In this article, we’ll look at how to change date format in Python Pandas bar plot, we use strftime.
How to change date format in Python Pandas bar plot?
To change date format in Python Pandas bar plot, we use strftime.
For instance, we write
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker as ticker
start = pd.to_datetime("5-1-2012")
idx = pd.date_range(start, periods= 365)
df = pd.DataFrame({'A':np.random.random(365), 'B':np.random.random(365)})
df.index = idx
df_ts = df.resample('W', how= 'max')
ax = df_ts.plot(kind='bar', x=df_ts.index, stacked=True)
ticklabels = ['']*len(df_ts.index)
ticklabels[::4] = [item.strftime('%b %d') for item in df_ts.index[::4]]
ticklabels[::12] = [item.strftime('%b %d\n%Y') for item in df_ts.index[::12]]
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
plt.gcf().autofmt_xdate()
plt.show()
We call item.strftime with the date format to format the item datetime into the date time string we want.
%b is the abbreviated month name like Jan, Feb, etc,
%d is the day of the month as a 2 digit number.
%Y is the 4 digit year number.
We have
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
to set the axes formatter.
And we call autofmt_xdate to format the dates.
Conclusion
To change date format in Python Pandas bar plot, we use strftime.