I draw some line plot for a monthly time series, which starts in 1999 with this code:
import pandas as pd
import matplotlib.pyplot as plt
matplotlib.style.use('ggplot')
url = ('https://raw.githubusercontent.com/mini-kep/parser-rosstat-kep/'
'master/data/processed/latest/dfm.csv')
dfm = pd.read_csv(url, converters={0: pd.to_datetime}, index_col=0)
ax = dfm.iloc[:,3:5].plot()
At this point I have major and minor ticks and x ticks lables. The desired change is alter the position of major ticks so that they start in 2000 and end 2020, every 5 years. I'm able to to that with code below (following this), but the price I pay is that the tick labels disappear. I was not able to bring them back with plt.xticks
. Another minor error that my ticks are now at year-end, not year start as wanted.
major_ticks = pd.date_range('2000', '2020', freq='5Y')
ax.set_xticks(major_ticks)
# below dows not help to add back major tick labels
# plt.xticks(label=[t.year for t in major_ticks])
minor_ticks = pd.date_range('1998', '2020', freq='Y')
ax.set_xticks(minor_ticks, minor=True)
Any suggestion is appreciated.
Update:
The code in my question followed this suggestion for changing the position of major ticks.
However, it got marked as duplicate of the question, that explains tick label formatting. It had useful clues, so the ultimate code that works is below:
# x_compat=True - an important part
ax = dfm.iloc[:,3:5].plot(x_compat=True)
# set minor ticks
minor_ticks = pd.date_range('1998', '2020', freq='YS')
ax.set_xticks(minor_ticks, minor=True)
# set major ticks
major_ticks = pd.date_range('2000', '2020', freq='5YS')
ax.xaxis.set_ticks(major_ticks, minor=False)
ax.xaxis.set_major_formatter(dates.DateFormatter('%Y'))
plt.gcf().autofmt_xdate(rotation=0, ha="center")