0

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

enter image description here

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)

enter image description here

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

enter image description here

Evgeny
  • 4,173
  • 2
  • 19
  • 39
  • "I'm able to to that with code ..." - I would rather say you are not able to do it, because you kill the ticks and labels using `xticks`. There are many questions on how to change the datetime ticks with matplotlib, did you look at any of them? – ImportanceOfBeingErnest Jun 20 '18 at 18:22
  • As for questions: I attached a link to the question I reproduced in my code. I managed to move the tick positions with it, but confused what call should reassign the labels. – Evgeny Jun 20 '18 at 18:27
  • there is no explicit call to xticks, it is commented out, unless .set_xticks calls it – Evgeny Jun 20 '18 at 18:30

0 Answers0