Matplotlib – Date manipulation to show the year tick every 12 months

Matplotlib provides powerful date formatting capabilities for time series visualization. To display year ticks every 12 months with proper month labeling, we use YearLocator and MonthLocator with custom formatters.

Understanding Date Locators and Formatters

Matplotlib's date handling uses two key components:

  • Locators − Determine where ticks are placed on the axis
  • Formatters − Control how dates are displayed as text

For year ticks every 12 months, we set major ticks for years and minor ticks for individual months.

Complete Example

Here's how to create a time series plot with year ticks showing every 12 months ?

import numpy as np
from matplotlib import pyplot as plt, dates as mdates
import pandas as pd

# Set figure configuration
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create sample time series data
date_range = pd.date_range("2020-01-01", "2021-06-01", freq="7D")
values = np.cumsum(np.random.normal(size=len(date_range)))
series = pd.Series(values, index=date_range)

# Set up date locators and formatters
years = mdates.YearLocator()        # Major ticks at years
months = mdates.MonthLocator()      # Minor ticks at months
monthsFmt = mdates.DateFormatter('%B')     # Full month names
yearsFmt = mdates.DateFormatter('\n%Y')    # Years with newline

# Convert to matplotlib date format
dates = series.index.to_pydatetime()

# Create plot
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(dates, series, linewidth=2)

# Configure minor ticks (months)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_minor_formatter(monthsFmt)
plt.setp(ax.xaxis.get_minorticklabels(), rotation=90)

# Configure major ticks (years)
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)

# Add labels
ax.set_title('Time Series with Year Ticks Every 12 Months')
ax.set_ylabel('Values')

plt.show()

Key Components Explained

Component Purpose Format String
YearLocator() Places major ticks at year boundaries N/A
MonthLocator() Places minor ticks at month boundaries N/A
'%B' Full month names (January, February, etc.) Month formatter
'\n%Y' Year with newline for better spacing Year formatter

Customizing the Display

You can customize the appearance further by adjusting tick parameters ?

import numpy as np
from matplotlib import pyplot as plt, dates as mdates
import pandas as pd

# Create sample data
date_range = pd.date_range("2019-01-01", "2022-12-31", freq="30D")
values = np.cumsum(np.random.normal(0, 1, size=len(date_range)))
series = pd.Series(values, index=date_range)

# Set up formatters with custom styling
years = mdates.YearLocator()
months = mdates.MonthLocator([1, 4, 7, 10])  # Quarterly months only
monthsFmt = mdates.DateFormatter('%b')        # Short month names
yearsFmt = mdates.DateFormatter('%Y')

fig, ax = plt.subplots(figsize=(10, 4))
ax.plot(series.index, series, color='blue', linewidth=1.5)

# Apply formatting
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_minor_formatter(monthsFmt)
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)

# Style the ticks
ax.tick_params(axis='x', which='minor', rotation=45, labelsize=8)
ax.tick_params(axis='x', which='major', labelsize=10, pad=15)

ax.set_title('Custom Date Formatting Example')
ax.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()

Conclusion

Use YearLocator() for major ticks and MonthLocator() for minor ticks to display years every 12 months. The DateFormatter with '%B' and '%Y' provides readable month and year labels.

Updated on: 2026-03-26T02:58:14+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements