Matplotlib datetime tick labels

Matplotlib plots with datetime axes can benefit from rotating axes tick labels or concise tick labels to avoid overlapping text.

Example code used in this post with synthetic data:

from matplotlib.pyplot import Figure
import matplotlib.dates as mdates
from datetime import datetime, timedelta

def datetime_range(start: datetime, end: datetime, step: timedelta) -> list[datetime]:
    """like range() for datetime"""
    return [start + i * step for i in range((end - start) // step)]

t = datetime_range(datetime(2021, 1, 1), datetime(2021, 1, 2), timedelta(minutes=30))
y = range(len(t))

Rotate datetime tick labels

If rotating tick labels, the overall axes typically need to be positioned to allow for the rotated labels, otherwise the tick labels can be cut off the figure edges. The axes position is updated automatically with constrained_layout option of figure().

fg = Figure(constrained_layout=True)
ax = fg.gca()

ax.plot(t, y)
ax.set_xlabel('time')
ax.set_ylabel('y')
ax.tick_params(axis="x", labelrotation=30)  # arbitrary rotation amount

fg.savefig("example.png")

Matplotlib date formatting

Matplotlib datetime axes have numerous formatting options. Here we show the ConciseFormatter, which may avoid the need to rotate tick labels.

fg = Figure(constrained_layout=True)
ax = fg.gca()

ax.plot(t, y)
ax.set_xlabel('time')
ax.set_ylabel('y')

ax.xaxis.set_major_formatter(
    mdates.ConciseDateFormatter(ax.xaxis.get_major_locator()))

fg.savefig("example.png")