I am plotting a monthly timeseries out of the following dataframe:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
df = pd.DataFrame({'date':pd.date_range('2001-01-01 00:00',end = '2001-12-31 23:59',freq='M'),
'value': np.array([1.63240641, 0.71793968, 0.15350684, 2.14915722, 0.45236403,
0.48638794, 0.74329402, 0.38316468, 0.96695818, 0.80566539,
1.23177184,0.556])})
df['Date'] = pd.to_datetime(df.date.astype(str), format='%Y-%m-%d',errors ='coerce')
df.set_index('Date',inplace = True)
df.drop(columns = 'date', axis = 1,inplace = True)
with the following code snippet:
fig,ax = plt.subplots()
ax.plot(df.index, df.value, color = 'tab:red', ls = '-.', marker = 'p')
# Major ticks every month.
# Set the locator
locator = mdates.MonthLocator() # every month
# Specify the format - %b gives us Jan, Feb...
formatter = mdates.DateFormatter('%b')
X = plt.gca().xaxis
X.set_major_locator(locator)
# Specify formatter
X.set_major_formatter(formatter)
plt.show()
But, if you notice the labeling in X axis starts from Feb instead of Jan. Feb
is displaying value of Jan
.
I have crosschecked my code many time but no luck yet.
Can anybody help me out on this issue. Thanks in advance.
P.S. I know pandas plot works fine here but for my specific purpose I need to plot it with matplotlib.