Matplotlib x axis date tick frequency

Viewed 4648

I have a simple dataframe that looks something like this (Year is the datetime index column):

Year         A          B
2018-01-01  1.049400    1.034076    
2017-01-01  1.056371    1.032066    
2016-01-01  1.063413    1.030055 

I graph the data using:

df['A'].plot()

df['B'].plot()

And get this graph with date tick labels every 5 years.

enter image description here

How can I make the year ticks appear every 2 (or any other number) of years?

1 Answers

Check this code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as md

x = range(2000, 2018, 1)
year = [f'{str(y)}-01-01' for y in x]

df = pd.DataFrame({'Year': year,
                   'A': np.sin(x),
                   'B': np.cos(x)})

df['Year'] = pd.to_datetime(df['Year'], format = '%Y-%m-%d').dt.date
df.set_index('Year', inplace = True)

fig, ax = plt.subplots(1, 1, figsize = (6, 4))

df['A'].plot()
df['B'].plot()

step = 2
ax.xaxis.set_major_locator(md.YearLocator(step, month = 1, day = 1))
ax.xaxis.set_major_formatter(md.DateFormatter('%Y'))

plt.legend()
plt.show()

You can manage the number of ticks with md.YearLocator(), in particular with the step value. I report the documentation for this method.
Pay attention to the type of the df index: in order to make the code work properly, the dataframe index column has to be a datetime.date, so I used the .dt.date method to convert from pandas._libs.tslibs.timestamps.Timestamp (because I built the dataframe in that way) to datetime.date. This depends on the type of data you have.
Some examples:

step = 2

enter image description here

step = 4

enter image description here

step = 10

enter image description here

Related