Rashida
Rashida

Reputation: 491

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

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

Upvotes: 22

Views: 10837

Answers (2)

EB613
EB613

Reputation: 171

I was having the same issue. The solution is really contained in the answer from @Ruthger Righart which I had trouble understanding at first, but the key change is using matplotlib pyplot plotting instead of the pandas plotting as mentioned here and in the link in the comments mentioned by @Trenton McKinney. First filter the data to the years you want to plot then call the plot like @Ruthger Righart did:

import matplotlib.pyplot as plt
fig,ax = plt.subplots()
ax.bar(df_month['Date'], df_month['Volume'])

Add the labels as you did originally.

Upvotes: 3

Ruthger Righart
Ruthger Righart

Reputation: 4921

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()

Upvotes: 2

Related Questions