Sub topic 12
Plotting time series with a datetime index
This chapter assumes you can build a DataFrame, call df.plot(), and know how set_index maps the index to the x axis. When the index holds dates, pandas treats the x axis as time. It spaces points by real elapsed time and picks readable tick labels.
Why a DatetimeIndex matters
If dates are stored as strings, pandas plots them as evenly spaced categories. A DatetimeIndex gives you proper time spacing, automatic date ticks, and tools like resample and slicing by date strings.
The usual pattern is to convert with pd.to_datetime, then call set_index.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
rng = np.random.default_rng(1)
days = pd.date_range("2026-01-01", periods=90, freq="D")
df = pd.DataFrame({
"date": days.astype(str),
"visits": 200 + np.cumsum(rng.normal(0, 8, 90)),
"signups": 20 + np.cumsum(rng.normal(0, 2, 90)),
})
df["date"] = pd.to_datetime(df["date"])
df = df.set_index("date")
df.plot(title="Daily traffic")
plt.show()Both columns share one axis here. Their scales differ, so signups looks flat. Use secondary_y="signups" to put it on a right-hand axis, or plot the columns in separate panels with subplots=True.
Smoothing and resampling
Daily data is often noisy. Two tools reduce it before plotting:
rolling(window).mean()keeps every date and averages over a moving window.resample(rule).agg()groups rows into coarser periods, such as weeks or months.
ax = df["visits"].plot(alpha=0.4, label="daily")
df["visits"].rolling(7).mean().plot(ax=ax, label="7-day average")
ax.legend()
plt.show()
df["visits"].resample("W").sum().plot.bar(title="Weekly visits")
plt.show()The first plot overlays two lines on one Axes by passing ax=ax. The first six rolling values are NaN, so that line starts a week later.
The second plot draws bars from a resampled Series. Bar charts treat each date as a category, so the tick labels show full timestamps. Format them if you want shorter text. Line and area charts keep the real time axis.
| Rule | Period |
|---|---|
| `"D"` | day |
| `"W"` | week, ending Sunday |
| `"MS"` | month start |
| `"QS"` | quarter start |
| `"YS"` | year start |
Selecting a date range
A sorted DatetimeIndex lets you slice with date strings. Both ends are included.
df.loc["2026-02-01":"2026-02-28"].plot(title="February")
plt.show()Common problems
- Dates stay as text. The axis shows evenly spaced labels, or
plotfinds no numeric data. Checkdf.index.dtype. It should bedatetime64[ns]. - Unsorted index. The line zigzags back and forth. Call
df.sort_index()first. - Gaps in the data. Missing dates break a line. Use
asfreq("D")to make them explicit, orinterpolate()to fill them. - Crowded tick labels. Increase
figsize, or rotate withrot=45.
Exercise
You have a DataFrame with a text column "day" and a numeric column "temp". Write the steps to plot monthly average temperature as a line chart.
Show answer
Convert and index, then resample and plot: df["day"] = pd.to_datetime(df["day"]), then df.set_index("day")["temp"].resample("MS").mean().plot(). Call plt.show() to display it.
Exercise
A line chart of dated data zigzags back and forth across the plot. What is the likely cause and the fix?
Show answer
The index is not sorted by date, so pandas connects points in row order. Call df.sort_index() before plotting.