Plot a series against its earlier values with a declared calendar, pair count and missing-period policy; separate serial dependence from a shared trend.
Lag plots: pair exact periods before reading dependence
Define the pair, not just the shift
A lag plot is a scatterplot of one series against itself at a fixed time offset. For lag 2, a mark might place a service's latency in week 47 on X and latency in week 49 on Y. The mark represents that ordered pair, not two independent records. A diagonal cloud may indicate persistence; a curve or alternating bands may expose nonlinear or periodic behavior. Neither shape proves a forecasting relationship. Name the measurement, its units, the calendar and the direction of the shift in the title or caption. State whether X is the earlier value, as it is here, because swapping axes changes the story a reader tells about high and low values. A lag plot answers a different question from autocorrelation, which reduces the paired values at each lag to a summary coefficient. The scatter keeps outliers and nonlinear shapes visible.
Use clock distance rather than row distance
A two-row shift is only a two-week lag when every row stands for exactly one week. If the export skips week 49, pairing the rows for weeks 48 and 50 as if they were adjacent creates a false lag-one mark. Key observations by a normalized period identifier, reject duplicate periods, and look up the target by adding the declared lag. A blank measurement stays blank. Do not replace it with zero just to keep the plot dense. The worked contract accepts consecutive integer period IDs; a calendar with fiscal exceptions needs a separate, explicit successor table. For daily timestamps, settle the time zone and daylight-saving policy before deriving the period ID. Calendar gaps, event alignment and missingness diagnostics provide the surrounding audit trail.
Publish the denominator and the missing-pair ledger
A plot with 83 points can look stable while half the intended periods vanished. Count all possible starts between the observed first and last period for the chosen lag, then report how many produced finite pairs. The omitted count includes a missing earlier period, a missing later period, or both; classify the reason separately if it affects the operational decision. The example constructs pairs by keyed lookup rather than materializing every period in a very sparse calendar. That makes its runtime depend on observed records, while the denominator still reflects the declared span. If a series has separate operating regimes, color by a predeclared regime or make small multiples with identical axes. Do not compute one overall trend line across a known sensor replacement. Small multiples and fit-scope rules make that split inspectable.
Check whether the shape survives detrending
Two adjacent values can line up along a diagonal simply because both rise over a long interval. That is not the same as a stable short-run dependency. Examine the original time plot, a differenced or detrended view when the analytical question calls for it, and at least one nearby lag. Keep the preprocessing contract attached to every panel. A seasonal process may create a strong lag at the cycle length even when the lag-one plot looks diffuse. Points can overlap, so opacity, hexbin counts or a marginal density may help without replacing the underlying pair count. Use symmetric numeric limits when the same unit appears on both axes; the identity line then has a literal equality meaning. Hexbin exposure, axis integrity and ordered trajectories solve different reading problems.
Worked contract
from math import isfinite
def latency_lag_pairs(readings: list[tuple[int, float | None]], lag: int):
if not isinstance(lag, int) or isinstance(lag, bool) or lag < 1:
raise ValueError("lag must be a positive number of periods")
by_week = {}
for week, latency_ms in readings:
if not isinstance(week, int) or isinstance(week, bool) or week in by_week:
raise ValueError("week IDs must be unique integers")
if latency_ms is not None and (isinstance(latency_ms, bool) or
not isinstance(latency_ms, (int, float)) or not isfinite(latency_ms) or
latency_ms < 0):
raise ValueError("latency must be finite, nonnegative or missing")
by_week[week] = latency_ms
if not by_week:
raise ValueError("at least one observed week is required")
first_week, last_week = min(by_week), max(by_week)
possible = max(0, last_week - first_week - lag + 1)
pairs = sorted((week, latency_ms, by_week[week + lag])
for week, latency_ms in by_week.items()
if week + lag <= last_week and latency_ms is not None
and by_week.get(week + lag) is not None)
return pairs, possible, possible - len(pairs)
weekly_latency = [(50, 83.0), (47, 72.0), (52, 79.0),
(48, 76.0), (49, None), (51, 77.0), (53, 75.0)]
pairs, possible, omitted = latency_lag_pairs(weekly_latency, lag=2)
assert pairs == [(48, 76.0, 83.0), (50, 83.0, 79.0),
(51, 77.0, 75.0)]
assert (possible, omitted) == (5, 2)Performance and operating cost
For N supplied weeks, validation and keyed pairing take expected O(N) time; sorting the output takes O(N log N). The dictionary and pair ledger use O(N) space. The algorithm does not iterate across empty calendar positions, so a sparse span does not force a span-sized allocation. In the worked series, weeks 47 through 53 offer five possible lag-two starts. Only three pairs have measurements at both ends; the two omitted starts touch missing week 49. The point (83, 79) belongs to weeks 50 and 52. A renderer should label that point by its earlier week, not by the array index of the row that happened to arrive first.
Common Mistakes
- Shifting by row count after missing calendar periods have been dropped.
- Drawing a diagonal reference line on independently scaled axes and calling it equality.
- Reporting the plotted point count without the eligible period-pair count.
- Reading trend-driven diagonal structure as a stable short-run forecasting law.
- Changing detrending, imputation or period definitions between comparison panels.
Validation drill
Take 83 weekly latency measurements, leave three outage weeks explicitly absent, and compare lag one, lag two and lag four. For each panel, publish the intended pair count, plotted pair count and missing-pair count. Then repeat on a declared detrended series and record which visual patterns remain.
