svglag-plot
Lag plot
Does today's value depend on the value k steps earlier (autocorrelation, randomness)?
How to read it
- Each point is one value against the value k steps earlier.
- A tight diagonal: today's value is close to the earlier one (strong autocorrelation).
- A shapeless cloud: the series looks random at that lag.
- Callout 1: A tight diagonal: strong dependence at this lag.
- 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
# Lag plot — Codesplash Chart Lab (recipe "lag-plot")
# controls: lag=1, colorTime=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
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:]
r = np.corrcoef(prev, cur)[0, 1]
fig = go.Figure(go.Scatter(x=prev, y=cur, mode="markers", marker=dict(size=6, opacity=0.8, color=np.arange(len(cur)), colorscale=[[0, SEQ[0]], [1, SEQ[-1]]])))
lo, hi = min(prev.min(), cur.min()), max(prev.max(), cur.max())
fig.add_scatter(x=[lo, hi], y=[lo, hi], mode="lines", line=dict(color=REF, dash="dash"), showlegend=False)
fig.update_layout(title=f"lag {k}: r = {r:.3f}", xaxis_title=f"temp_c[t − {k}]", yaxis_title="temp_c[t]", showlegend=False)
fig.show()Needs pandas, numpy, plotly · reads lag-plot-demo.csv · app theme from the optional codesplash helper
# Lag plot — Codesplash Chart Lab (recipe "lag-plot")
# controls: lag=1, colorTime=true
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("lag-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["date"]] <- as.POSIXct(df[["date"]], tz = "UTC")
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
d <- df[!is.na(df[["date"]]) & !is.na(df[["temp_c"]]), , drop = FALSE]
d <- d[order(d[["date"]]), , drop = FALSE] # lags count observations, not calendar time
v <- d[["temp_c"]]
k <- max(1, min(1, max(1, length(v) - 2)))
pairs <- data.frame(prev = utils::head(v, -k), cur = utils::tail(v, -k))
pairs$t <- seq_len(nrow(pairs))
r <- stats::cor(pairs$prev, pairs$cur) # Pearson r of the plotted pairs
p <- ggplot(pairs, aes(prev, cur)) +
geom_abline(slope = 1, intercept = 0, colour = ref_col, linetype = "dashed") +
geom_point(aes(colour = t), size = 1.4, alpha = 0.8) +
scale_colour_gradient(low = seq_ramp[1], high = seq_ramp[2], guide = "none") +
labs(x = paste0("temp_c", "[t − ", k, "]"), y = "temp_c[t]", title = sprintf("lag %d: r = %.3f", k, r)) +
coord_equal() + theme_cs
print(p)Needs ggplot2 · reads lag-plot-demo.csv · app theme from the optional codesplashr helper
-- Lag plot — Codesplash Chart Lab (recipe "lag-plot")
-- controls: lag=1, colorTime=true
-- lag-1 pairs in time order and their Pearson r
WITH s AS (
SELECT "temp_c" AS cur, lag("temp_c", 1) OVER (ORDER BY "date") AS prev
FROM read_csv('lag-plot-demo.csv')
WHERE "temp_c" IS NOT NULL AND "date" IS NOT NULL
)
SELECT prev, cur, corr(prev, cur) OVER () AS r
FROM s
WHERE prev IS NOT NULL;Needs duckdb · reads lag-plot-demo.csv