Plotting time in Python
Matplotlib understands datetimes; the formatter decides how they read.
import matplotlib
matplotlib.use("Agg")
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
from datetime import date, timedelta
start = date(2026, 7, 20)
days = [start + timedelta(days=n) for n in range(10)]
tpm = [88, 90, 92, 97, 99, 101, 104, 103, 107, 110]
figure, axes = plt.subplots(figsize=(7, 3))
axes.plot(days, tpm, marker=".")
axes.xaxis.set_major_formatter(mdates.DateFormatter("%d %b"))
axes.xaxis.set_major_locator(mdates.DayLocator(interval=2))
figure.autofmt_xdate()
figure.savefig("dates.png")
How it works
- Pass datetimes straight to
plot. DateFormattercontrols the tick labels.autofmt_xdaterotates them so they fit.
Keywords and builtins used here
asforrange
The run, in numbers
- Lines
- 17
- Characters to type
- 527
- Tokens
- 155
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 85 seconds.
Step 3 of 4 in Reading the plot, step 12 of 14 in Plotting with matplotlib.