svgperiodogram
Periodogram
Which cycle lengths carry the most variation in the series?
How to read it
- Read each peak as a cycle: higher means more variance at that frequency.
- Convert: period = 1 / frequency, so a peak at 0.083 is a 12-step cycle.
- Look for harmonics: peaks at multiples of the main frequency.
- Callout 1: The strongest cycle, labelled with its period.
- Callout 2: A harmonic of the main cycle.
- Callout 3: Lower peaks in the rest of the spectrum are mostly noise.
Watch out
- A raw periodogram is noisy: isolated tall spikes occur by chance, so confirm a cycle with a test or more data.
Defaults
- Season length to mark (0 = none)
- 0
- Mark the frequency of this season and its multiples.
- Range 0 to 10,000, step 1
- Log scale
- On
- Space the axis by ratios, which suits values spanning orders of magnitude.
Pinned in the code
- I(f_j) = |Σ (x_t − x̄) e^{−2πi f_j t}|² / n at f_j = j/n, j = 1…⌊n/2⌋ — unsmoothed and untapered (R spec.pgram with taper = 0, detrend = FALSE, demean = TRUE, times n).
- A season of length m shows as a peak at 1/m and its harmonics k/m; a trend piles power near frequency 0.
- Raw periodogram ordinates are noisy (each has two degrees of freedom); smooth before reading fine detail.
# Periodogram — Codesplash Chart Lab (recipe "periodogram")
# controls: period=0, log=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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("periodogram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
def ordered(d, x, cols):
"""Rows with the needed values, sorted by the time column (stable); row order when there is none."""
d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
return d.sort_values(x, kind="stable") if x else d
def time_of(d, x):
return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = None
Y = "value"
PERIOD, LOG = 0, True # season length to mark (0 = none)
v = ordered(df, X, [Y])[Y].to_numpy(dtype=float)
n = len(v)
j = np.arange(1, n // 2 + 1)
spec = np.abs(np.fft.fft(v - v.mean())[j]) ** 2 / n # raw periodogram at Fourier frequencies j/n
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(j / n, spec, color=PALETTE[0], linewidth=1.4)
if PERIOD > 0:
ax.axvline(1 / PERIOD, color=REF, linestyle="--", label=f"period {PERIOD:g}")
ax.legend(frameon=False)
if LOG:
ax.set_yscale("log")
ax.set_xlabel("frequency (cycles per observation)")
ax.set_ylabel("spectral density")
plt.show()Needs pandas, numpy, matplotlib · reads periodogram-demo.csv · app theme from the optional codesplash helper
# Periodogram — Codesplash Chart Lab (recipe "periodogram")
# controls: period=0, log=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("periodogram-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
def ordered(d, x, cols):
"""Rows with the needed values, sorted by the time column (stable); row order when there is none."""
d = d.dropna(subset=[c for c in cols if c] + ([x] if x else []))
return d.sort_values(x, kind="stable") if x else d
def time_of(d, x):
return d[x] if x else pd.Series(np.arange(1, len(d) + 1), index=d.index)
X = None
Y = "value"
PERIOD, LOG = 0, True
v = ordered(df, X, [Y])[Y].to_numpy(dtype=float)
n = len(v)
j = np.arange(1, n // 2 + 1)
spec = np.abs(np.fft.fft(v - v.mean())[j]) ** 2 / n
fig = go.Figure(go.Scatter(x=j / n, y=spec, mode="lines", line=dict(color=PALETTE[0]), customdata=n / j, hovertemplate="f = %{x:.4f} (period %{customdata:.2f})<br>%{y:.4g}<extra></extra>"))
if PERIOD > 0:
fig.add_vline(x=1 / PERIOD, line=dict(color=REF, dash="dash"), annotation_text=f"period {PERIOD:g}")
fig.update_layout(xaxis_title="frequency (cycles per observation)", yaxis_title="spectral density", yaxis_type="log" if LOG else "linear")
fig.show()Needs pandas, numpy, plotly · reads periodogram-demo.csv · app theme from the optional codesplash helper
# Periodogram — Codesplash Chart Lab (recipe "periodogram")
# controls: period=0, log=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("periodogram-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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
ordered <- function(d, x, cols) {
keep <- stats::complete.cases(d[, c(cols, x), drop = FALSE])
d <- d[keep, , drop = FALSE]
if (!is.null(x)) d[order(d[[x]]), , drop = FALSE] else d
}
time_of <- function(d, x) if (is.null(x)) seq_len(nrow(d)) else d[[x]]
x_col <- NULL
y_col <- "value"
PERIOD <- 0
LOG <- TRUE
v <- ordered(df, x_col, y_col)[[y_col]]
n <- length(v)
j <- seq_len(n %/% 2)
spec <- Mod(stats::fft(v - mean(v)))[j + 1]^2 / n # raw periodogram at j/n
pg <- data.frame(freq = j / n, spec = spec)
p <- ggplot(pg, aes(freq, spec)) + geom_line(colour = cs_cat[1]) +
{ if (PERIOD > 0) geom_vline(xintercept = 1 / PERIOD, colour = ref_col, linetype = "dashed") } +
{ if (LOG) scale_y_log10() } + labs(x = "frequency (cycles per observation)", y = "spectral density") + theme_cs
print(p)Needs ggplot2 · reads periodogram-demo.csv · app theme from the optional codesplashr helper