0

I am trying to format the dates in a dataframe plot whose index is a time series.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


periods = 30
df = pd.DataFrame(np.random.randint(0, 20, size=periods),
                  columns=["Value"],
                  index=pd.date_range("20180306", periods=periods))
ax = df.plot(kind='bar')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d %Y'))
plt.show()

The problem: Dates on the X-axis start at the epoch, so the chart shows "Jan 01 1970" as the first date.

Note that this problem goes away if I don't use a "bar" plot kind.

Any idea of how to fix this?

sagism
  • 881
  • 4
  • 11
  • 18
  • Does this answer your question? [Matplotlib DateFormatter for axis label not working](https://stackoverflow.com/questions/33743394/matplotlib-dateformatter-for-axis-label-not-working) – Asmus Jul 22 '20 at 05:30

1 Answers1

1

Apparently, there's some issue with date formatting and bar charts. Here's a workaround:

import matplotlib.dates as mdates

periods = 30
df = pd.DataFrame(np.random.randint(0, 20, size=periods),
                  columns=["Value"],
                  index=pd.date_range("20180306", periods=periods))
ax = df.plot(kind='bar')
plt.gca().xaxis.set_major_formatter(plt.FixedFormatter(df.index.to_series().dt.strftime('%b %d %Y')))

plt.show()

The output is: enter image description here

Roy2012
  • 11,755
  • 2
  • 22
  • 35