Using datetime as ticks in Matplotlib

Althought this answer works well, for this case you can avoid defining your own FuncFormatter by using the pre-defined ones from matplotlib for dates, by using matplotlib.dates rather than matplotlib.ticker:

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

# Define time range with 12 different months:
# `MS` stands for month start frequency 
x_data = pd.date_range('2018-01-01', periods=12, freq='MS') 
# Check how this dates looks like:
print(x_data)
y_data = np.random.rand(12)
fig, ax = plt.subplots()
ax.plot(x_data, y_data)
# Make ticks on occurrences of each month:
ax.xaxis.set_major_locator(mdates.MonthLocator())
# Get only the month to show in the x-axis:
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
# '%b' means month as locale’s abbreviated name
plt.show()

Obtaining:

DatetimeIndex(['2018-01-01', '2018-02-01', '2018-03-01', '2018-04-01',
           '2018-05-01', '2018-06-01', '2018-07-01', '2018-08-01',
           '2018-09-01', '2018-10-01', '2018-11-01', '2018-12-01'],
          dtype="datetime64[ns]", freq='MS')

Plot showing abbreviated months on the x-axis

Leave a Comment