I am plotting time series data using DataFrame.plot()
method of pandas. Below is the code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy.random as rn
series_dt = pd.Series(rn.randint(1000,10000,24),index=pd.date_range(start='2020-01-01',periods=24,freq='MS'))
ax = series_dt.plot(figsize=(10,7),rot=45)
I got a plot, but now I want to place xticks with dates at specific locations that I specify. This is my attempt at doing this:
xticks_positions = series_dt.index[::2]
ax.set_xticks(xticks_positions)
ax.set_xticklabels(xticks_positions.strftime('%b %Y'))
The problem that I am facing is that some labels and ticks from the previous plot are also there even after setting new ticks and their labels. I don't want the ticks and labels from the previous plot. I just to see the ticks and labels that I set.
The index you are using is in pandas date format. You need to convert it to python date so that it is understood by matplotlib. Once this is done, you can plot the same and control the date format and frequency using set_major_locator()
and set_major_formatter()
in matplotlib.dates. The updated code is shown below. Hope this is what you are looking for.
ind=pd.date_range(start='2020-01-01',periods=24,freq='MS')
ind = [pd.to_datetime(date, format='%b %Y').date() for date in ind] ##Convert like this before using
series_dt = pd.Series(rn.randint(1000,10000,24),index=ind)
ax = series_dt.plot(figsize=(10,7),rot=45)
## Your code removed
#xticks_positions = series_dt.index[::2]
#ax.set_xticks(xticks_positions)
#ax.set_xticklabels(xticks_positions).strftime('%b %Y'))
## Added code to control frequency and date format
import matplotlib.dates as mdates
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=2)) ##Once in 2 months
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y')) ##Format of label
plt.gcf().autofmt_xdate()