Plotting Dates & Time
Time series are among the most common things to plot: daily sales, hourly temperatures, monthly users. Matplotlib understands Python datetime objects and NumPy datetime64 arrays directly, and its matplotlib.dates module controls how dates appear on the axis.
Plotting datetime values
Pass a list of dates as x and Matplotlib picks sensible date ticks:
from datetime import date, timedelta
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
start = date(2024, 3, 1)
days = [start + timedelta(days=i) for i in range(14)]
steps = [6400, 7200, 5100, 8800, 9100, 12000, 11500,
6900, 7600, 5800, 9400, 8700, 13100, 10200]
fig, ax = plt.subplots(figsize=(7, 3.5), layout="constrained")
ax.plot(days, steps, marker="o")
ax.set(ylabel="Steps", title="Two weeks of walking")
ax.tick_params(axis="x", rotation=30)
plt.show()
print("First day:", days[0], "| last day:", days[-1])
print("First day as a number:", mdates.date2num(days[0]), "days since 1970-01-01")First day: 2024-03-01 | last day: 2024-03-14
First day as a number: 19783.0 days since 1970-01-01
Internally, Matplotlib converts dates to floating-point numbers (days since 1970-01-01) and remembers that the axis holds dates, so it formats the ticks as dates.
NumPy date ranges
NumPy's datetime64 makes regular date ranges easy: np.arange works with dates and a step unit:
import numpy as np
import matplotlib.pyplot as plt
days = np.arange("2024-01-01", "2024-07-01", dtype="datetime64[D]")
t = np.arange(days.size)
rng = np.random.default_rng(30)
price = 100 + 0.08 * t + 4 * np.sin(t / 15) + rng.normal(0, 1.2, days.size).cumsum() * 0.4
fig, ax = plt.subplots(figsize=(8, 3.5), layout="constrained")
ax.plot(days, price, lw=1.2)
ax.set(ylabel="Price ($)", title="Six months of prices")
plt.show()
print("Days:", days.size, "| first:", days[0], "| last:", days[-1])
print(f"Start {price[0]:.2f}, end {price[-1]:.2f}")Days: 182 | first: 2024-01-01 | last: 2024-06-30
Start 100.76, end 117.99
Controlling date ticks
matplotlib.dates offers locators and formatters specialised for dates:
| Locator | Places ticks … |
|---|---|
DayLocator(interval=n) |
every n days |
WeekdayLocator(byweekday=MO) |
on given weekdays |
MonthLocator() |
on the 1st of each month (bymonth= to choose) |
YearLocator() |
on 1 January |
AutoDateLocator() |
automatically (the default) |
Formatters use strftime codes: %Y year, %m month number, %b short month name, %d day, %a short weekday, %H:%M time.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
days = np.arange("2024-01-01", "2025-01-01", dtype="datetime64[D]")
doy = np.arange(days.size)
daylight = 12 + 4.5 * np.sin((doy - 80) / 366 * 2 * np.pi) # hours of daylight
fig, ax = plt.subplots(figsize=(8, 3.5), layout="constrained")
ax.plot(days, daylight, color="orange")
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b"))
ax.set(ylabel="Daylight (h)", title="Day length over 2024")
ax.grid(alpha=0.3)
plt.show()
longest = days[daylight.argmax()]
print("Longest day:", longest, f"({daylight.max():.1f} h)")
print("Tick labels:", [t.get_text() for t in ax.get_xticklabels()][:4], "...")Longest day: 2024-06-20 (16.5 h)
Tick labels: ['Jan', 'Feb', 'Mar', 'Apr'] ...
Concise date formatting
The ConciseDateFormatter shows only what changes between ticks and puts the rest (year, month) in an offset label. It saves space and is a great default for long series:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
hours = np.arange("2024-05-10T00", "2024-05-13T00", dtype="datetime64[h]")
h = np.arange(hours.size)
temp = 15 + 6 * np.sin((h - 9) / 24 * 2 * np.pi)
fig, ax = plt.subplots(figsize=(8, 3.5), layout="constrained")
ax.plot(hours, temp, color="C3")
locator = mdates.AutoDateLocator()
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(locator))
ax.set(ylabel="°C", title="Three days of hourly temperature")
plt.show()
print("Hourly readings:", hours.size)Hourly readings: 72
Rotating labels and marking events
When date labels are long, fig.autofmt_xdate() rotates and right-aligns them. Vertical lines and spans mark events in time:
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
weeks = np.arange("2024-01-01", "2024-07-01", 7, dtype="datetime64[D]")
signups = np.array([120, 125, 131, 128, 140, 138, 150, 210, 260, 240, 230, 225, 228,
232, 236, 240, 246, 250, 255, 252, 260, 268, 270, 275, 280, 283])
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(weeks, signups, marker=".")
launch = datetime(2024, 2, 19)
ax.axvline(launch, color="C3", linestyle="--")
ax.annotate("App launch", xy=(launch, 150), xytext=(10, 0), textcoords="offset points", color="C3")
ax.xaxis.set_major_formatter(mdates.DateFormatter("%d %b %Y"))
fig.autofmt_xdate()
ax.set_ylabel("Weekly sign-ups")
plt.show()
print("Weeks:", weeks.size, "| first week:", weeks[0], "| launch:", launch.date())Weeks: 26 | first week: 2024-01-01 | launch: 2024-02-19
Tip: pandas Series with a
DatetimeIndexplot dates automatically, and the next lesson shows how pandas and Matplotlib work together.
Test yourself
Which formatter string shows dates like "Mar 05"?
- "%m %d"
- "%b %d"
- "%B %Y"
- "%d/%m"
What does mdates.MonthLocator() do?
- Formats months as text
- Places a tick at the start of every month
- Converts strings to dates
- Shows only one month
What is the advantage of ConciseDateFormatter?
- It sorts the dates
- It shows only the changing part of each date and moves the rest to an offset label
- It converts time zones
- It removes the x axis