sagism
sagism

Reputation: 921

Formatting dates on pandas timeseries plot messes up the date

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?

Upvotes: 0

Views: 251

Answers (1)

Roy2012
Roy2012

Reputation: 12523

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

Upvotes: 1

Related Questions