1

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

Which gave me the plot: enter image description here

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.

Peshal1067
  • 183
  • 1
  • 10
  • 1
    print `pd.date_range('2001-01-01 00:00',end = '2001-12-31 23:59',freq='M')` and have a look at the dates you're getting – Riley Nov 02 '21 at 05:14
  • 1
    I'm guessing you want `freq="MS"` instead – Riley Nov 02 '21 at 05:15
  • Tried your suggestion and works well. Thanks a lot @ Riley – Peshal1067 Nov 02 '21 at 05:19
  • 1
    [Pandas date_range to generate monthly data at beginning of the month](https://stackoverflow.com/questions/34915828/pandas-date-range-to-generate-monthly-data-at-beginning-of-the-month) – JohanC Nov 02 '21 at 06:49

0 Answers0