Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas plot displays wrong months from datetime on x-axis

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 :

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading