Skip to content
svglag-plot

Lag plot

Does today's value depend on the value k steps earlier (autocorrelation, randomness)?

Demo data · seed 20261101 · 731 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Each point is one value against the value k steps earlier.
  2. A tight diagonal: today's value is close to the earlier one (strong autocorrelation).
  3. A shapeless cloud: the series looks random at that lag.
  1. Callout 1: A tight diagonal: strong dependence at this lag.
  2. Callout 2: The lag, the correlation and the row count.

Watch out

  • A trend alone produces a tight diagonal. Remove the trend before reading it as memory.

Defaults

Lag k (observations)
1
How many steps back to compare each value with.
Range 1 to 60, step 1
Colour by time
On
Fade the path from early to late so you can follow its direction.

Pinned in the code

  • Rows are sorted by the time column; the lag counts observations, not calendar time (resample irregular series first).
  • Points are (y[t − k], y[t]); the dashed line is y[t] = y[t − k]; r is the Pearson correlation of the plotted pairs (close to, but not identical to, the ACF at lag k, which uses the full-series mean and denominator n).
  • Structure along the diagonal means autocorrelation; a shapeless cloud suggests randomness.
# Lag plot — Codesplash Chart Lab (recipe "lag-plot")
# controls: lag=1, colorTime=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]

df = pd.read_csv("lag-plot-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])

_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"])  # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"])  # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
d = df.dropna(subset=["date", "temp_c"]).sort_values("date", kind="stable")  # lags count observations, not calendar time
v = d["temp_c"].to_numpy(dtype=float)
k = max(1, min(1, max(1, len(v) - 2)))
prev, cur = v[:-k], v[k:]  # pairs (y[t − k], y[t])
r = np.corrcoef(prev, cur)[0, 1]  # Pearson r of the plotted pairs (close to, not equal to, the ACF at lag k)
fig, ax = plt.subplots(figsize=(5.5, 5))
ax.scatter(prev, cur, c=np.arange(len(cur)), cmap=LinearSegmentedColormap.from_list("time", [SEQ[0], SEQ[-1]]), s=14, alpha=0.8, edgecolors="none")  # early → late
lo, hi = min(prev.min(), cur.min()), max(prev.max(), cur.max())
ax.plot([lo, hi], [lo, hi], color=REF, linestyle="--", linewidth=1)  # y[t] = y[t − k]
ax.set_xlabel(f"temp_c[t − {k}]")
ax.set_ylabel("temp_c[t]")
ax.set_title(f"lag {k}: r = {r:.3f}", fontsize=10, loc="left")
plt.show()

Needs pandas, numpy, matplotlib · reads lag-plot-demo.csv · app theme from the optional codesplash helper