Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 427
Rashida Avatar asked Nov 18 '25 10:11

Rashida


2 Answers

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.

like image 71
EB613 Avatar answered Nov 20 '25 00:11

EB613


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()
like image 34
Ruthger Righart Avatar answered Nov 19 '25 22:11

Ruthger Righart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!