I am trying to plot stacked bar chart using pandas and matplotlib. I want months to be located on x-axis from datetimes. But It always shows "jan", despite the month given.
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
from datetime import datetime
df = pd.DataFrame({'value1':[1,2], 'value2':[5,4]},
index=[datetime(year=2020, month=3, day=3),
datetime(year=2020, month=4, day=6)])
date_fmt = mdates.DateFormatter('%b')
df.plot(kind='bar', stacked=True)
ax = plt.gca()
ax.xaxis.set_major_formatter(date_fmt)
How to change the code so that it displays correct month on x-axis?
I tried to also display year and day for debugging purposes, and it gives ‘Jan 01 1970’ for the first bar and ‘Jan 02 1970’ for the second.
>Solution :
Why not simply strftime the DatetimeIndex as ("%b") ?
df.index = df.index.strftime('%b') # <-- add this line and remove the mdates formatter
ax = df.plot(kind='bar', stacked=True) # or `df.plot.bar(stacked=True)`
plt.show();
Ouptut :
