DateFormatter is bringing 1970 as year not the original year in the dataset

Viewed 3104

I am trying to plot time series data. But x axis ticks are not coming the way it should. I wanted to out mont and year as x axis ticks. here is my code

from matplotlib.dates import DateFormatter
import matplotlib.dates as mdates
fig,ax = plt.subplots()
df_month.loc['2017', "Volume"].plot.bar(color='blue', ax=ax)
ax.set_ylabel("Volume")
ax.set_title("Volume")
date_form = DateFormatter("%y-%m")
ax.xaxis.set_major_formatter(date_form)

plt.xticks(rotation=45)
plt.show()

The output looks like this enter image description here What am I doing wrong? Please help.

My dataset looks like this: enter image description here

Here is df_month data: enter image description here

1 Answers

The following gives the right x-axis labels.

Import modules

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

Example data

df_month = pd.DataFrame({'Date':['2006-01-03', '2006-02-04', '2006-02-08'], 'Volume':[24232729, 20553479, 20500000]}) # '2006-01-03', '2006-01-04'

df_month['Date'] = pd.to_datetime(df_month['Date'])

Plotting

fig,ax = plt.subplots()
ax.set_ylabel("Volume")
ax.set_title("Volume")

ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.bar(df_month['Date'], df_month['Volume'])

plt.xticks(df_month['Date'], rotation=90)
plt.show()
Related