Correlation with a circle
Pearson on raw angles is wrong. Use Jammalamadaka–SenGupta for two angles and Mardia's circular–linear correlation for an angle and a measurement.
What runs in CodeSplash
- Circular correlation (angle–angle and angle–linear) Verified in Python and R
You will be able to
- Say why Pearson correlation fails on angles
- Choose between angle–angle and angle–linear correlation
- Encode a cycle with sine and cosine for ordinary models
Read first
Wrapping breaks Pearson
ReadPearson's r on raw bearings treats 359° and 1° as far apart. The same data can give different answers depending on where you start the compass, so its value depends on an arbitrary choice.
Circular correlations don't. Two kinds cover most questions:
- Angle with angle: wind direction and gust direction. Jammalamadaka–SenGupta.
- Angle with a measurement: wind direction and speed. Mardia's circular–linear correlation.
Does direction predict speed?
PredictPredict first
Winds from one quarter blow harder, here by design of the simulated data. Mardia's circular–linear correlation runs from 0 to 1.
How strong is the association between direction and speed?
Reveal
Strong: 0.83, from 240 observations, p < .001. Note that it has no sign: "direction" can't increase. It says speed depends on direction, not which way.
How it's built
ReadCorrelate the measurement with and with , and combine them, allowing for the correlation between the two:
Here, = 0.04 and = −0.82. Almost all of it runs through the sine term, meaning east–west direction, so speed is highest on one side of the compass.
Two angles together
Readr = 0.92, p < .001, n = 240
- Circular correlation r (Jammalamadaka–SenGupta)
- 0.9153
- p
- < .001
Plots
View data
| direction | gust_direction |
|---|---|
| 182.70 | 175 |
| 228.50 | 249.40 |
| 313.40 | 285.70 |
| 353.10 | 353.40 |
| 308.70 | 340.10 |
| 249.60 | 269.70 |
| 242.20 | 258.30 |
| 281 | 295.20 |
| 231 | 197.20 |
| 158.10 | 177.90 |
| 344.30 | 31.100 |
| 247.60 | 243.60 |
| 231.50 | 241.80 |
| 284.20 | 310.90 |
| 234.50 | 266 |
| 328.40 | 342.50 |
| 308.50 | 347.90 |
| 190.40 | 188.10 |
| 318.70 | 269.90 |
| 332.70 | 333.80 |
| 245.70 | 256.70 |
| 277.20 | 244.40 |
| 251 | 267.60 |
| 302 | 303.10 |
| 306.60 | 309.30 |
| 184.50 | 171.30 |
| 183.20 | 197 |
| 333 | 323.40 |
| 345.40 | 12.500 |
| 231.50 | 234.90 |
| 213.20 | 207.60 |
| 269.10 | 295.90 |
| 222.90 | 229.80 |
| 273.30 | 239.20 |
| 189.50 | 194.20 |
| 252.50 | 236.90 |
| 212.80 | 217.30 |
| 228.10 | 226.20 |
| 228.60 | 229.20 |
| 271.90 | 256.20 |
| 273.80 | 237.70 |
| 242.80 | 264.20 |
| 45.700 | 59.300 |
| 205.10 | 204.50 |
| 297.90 | 332.20 |
| 281 | 265.10 |
| 281.10 | 257.60 |
| 351.20 | 334.30 |
| 286 | 300.40 |
| 258.30 | 246.70 |
| 221.60 | 223.80 |
| 230.60 | 245.70 |
| 257.50 | 261.60 |
| 283.40 | 267.30 |
| 293.50 | 294.20 |
| 221.40 | 228.60 |
| 313.50 | 332.40 |
| 254.90 | 260.80 |
| 269.30 | 292 |
| 302.30 | 259.20 |
First 60 of 240 rows.
Assumptions
- Independent pairs — One pair of values per unit (no repeated readings).
- p-value: large-sample.
The exact R script · R R version 4.5.1 (2025-06-13)
# Circular correlation (angle–angle and angle–linear)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method circular.correlation 1.0.1 · spec 211ae55e6629e72e
# Dataset: ci_wind (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ci_wind.parquet", col_select = c("direction", "gust_direction")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("direction", "gust_direction")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("direction", "gust_direction")) # infinite values stop the run (registry/errors.yaml)
# %% Angles
# Angles become radians in [0, 2*pi): numeric values in the chosen unit, or a timestamp's position in
# its daily / weekly / yearly cycle (UTC). Axial data (0° = 180°) are doubled before testing.
units <- "degrees"
period <- NULL
disp_units <- switch(units, time_of_day = "hours", day_of_week = "weekday", day_of_year = "doy", units)
axial <- FALSE
a_name <- "direction"
theta <- cs_circ_angles(df[[a_name]], units, period)
work <- if (axial) cs_circ_wrap(2 * theta) else theta
turn <- 2 * pi * (if (axial) 0.5 else 1)
unit_scale <- (if (disp_units == "custom") period else switch(disp_units, degrees = 360, radians = 2 * pi, hours = 24, weekday = 7, month = 12, doy = 365.25)) / (2 * pi)
show <- function(rad) cs_circ_from_radians(rad %% turn, disp_units, period)
lab <- function(rad) cs_circ_label(rad %% turn, units, period)
chart_angles <- cs_circ_from_radians(theta, disp_units, period)
chart_controls <- list(units = if (disp_units != "custom") disp_units else "radians",
orientation = if (disp_units %in% c("degrees", "hours")) "compass" else "math")
if (disp_units == "custom") chart_angles <- theta
# %% Correlation
o_name <- "gust_direction"
kind <- "circular"
calibration <- "approximate"
seed <- 42 # shared Wichmann-Hill stream: Python draws the same permutations
if (kind == "circular") {
other <- cs_circ_angles(df[[o_name]], units, period)
other_work <- if (axial) cs_circ_wrap(2 * other) else other
} else {
other <- as.numeric(df[[o_name]])
other_work <- other
}
# A correlation needs pairs that vary: 2 pairs for two angles, 3 for an angle and a linear variable.
cs_check_rows(length(work), if (kind == "circular") 2 else 3, "A circular correlation")
cs_check_not_constant(theta, a_name)
cs_check_not_constant(other, o_name)
r <- cs_circ_correlation(work, other_work, kind = kind, calibration = calibration, n_perm = 9999, seed = seed)
n <- length(work)
# %% Assumptions
assumptions <- list(list(key = "independence", label = "Independent pairs", status = "info", detail = "One pair of values per unit (no repeated readings)."))
if (n < 25 && calibration != "permutation") warnings <- c(warnings, "Fewer than 25 pairs: the large-sample p-value is approximate; use permutation.")
# %% Result
p <- r$p
if (kind == "circular") {
stat <- r$r
stat_label <- "Circular correlation r (Jammalamadaka–SenGupta)"
symbol <- "r"
test_txt <- sprintf("z = %.3f", r$z)
} else {
stat <- r$r
stat_label <- "Circular–linear correlation R (Mardia)"
symbol <- "R"
test_txt <- sprintf("nR² = %.3f on 2 df", r$statistic)
}
values <- list(n = n, other_type = kind, r = r$r, p = p, z = r$z, r2 = r$r2, statistic = r$statistic,
r_xc = r$r_xc, r_xs = r$r_xs, r_cs = r$r_cs, p_asymptotic = r$p_asymptotic, n_perm = r$n_perm)
how <- if (calibration == "permutation") sprintf("permutation (%d shuffles, seed %d)", as.integer(r$n_perm), as.integer(seed)) else "large-sample"
summary <- paste0(sprintf("%s correlation between %s and %s (n = %d): %s = %.3f (%s, %s). ", if (kind == "circular") "Circular" else "Circular–linear",
a_name, o_name, n, symbol, stat, test_txt, cs_fmt_p(p)),
if (p < 0.05) "The two are associated." else "No evidence of an association.")
if (kind == "linear") summary <- paste0(summary, " R is between 0 and 1 and has no sign: it measures how well a sinusoidal pattern in the angle predicts the linear variable.")
chart_x <- chart_angles
chart_y <- if (kind == "circular") cs_circ_from_radians(other, disp_units, period) else other
take <- seq_len(min(n, 5000))
cs_publish(list(
method = "circular.correlation",
methodVersion = "1.0.1",
title = "Circular correlation",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("%s = %s, %s, n = %d", symbol, cs_fmt_num(stat), cs_fmt_p(p), n),
statistics = list(list(key = "r", label = stat_label, value = stat), list(key = "p", label = "p", value = p, format = "p")),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("p-value: %s.", how)),
values = values,
charts = list(cs_chart("scatter", "scatter", paste(o_name, "against", a_name),
list(x = cs_col(a_name, chart_x[take], "numeric"), y = cs_col(o_name, chart_y[take], "numeric")), list(fit = "none")))
))
r = 0.92, p < .001, n = 240
- Circular correlation r (Jammalamadaka–SenGupta)
- 0.9153
- p
- < .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Independent pairs — One pair of values per unit (no repeated readings).
- p-value: large-sample.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Circular correlation (angle–angle and angle–linear)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method circular.correlation 1.0.1 · spec 211ae55e6629e72e
# Dataset: ci_wind (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import circular
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ci_wind.parquet", columns=["direction", "gust_direction"])
n_input = len(df)
df = df.dropna(subset=["direction", "gust_direction"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["direction", "gust_direction"]) # infinite values stop the run (registry/errors.yaml)
# %% Angles
# Angles become radians in [0, 2π): numeric values in the chosen unit, or a timestamp's position in its
# daily / weekly / yearly cycle (UTC). Axial data (0° ≡ 180°) are doubled before testing.
units = "degrees"
period = None
disp_units = {"time_of_day": "hours", "day_of_week": "weekday", "day_of_year": "doy"}.get(units, units)
axial = False
a_name = "direction"
theta = circular.angles(df[a_name] if units in circular.CYCLES else df[a_name].to_numpy(dtype=float), units, period)
work = circular.wrap(2.0 * theta) if axial else theta
turn = 2.0 * np.pi * (0.5 if axial else 1.0)
unit_scale = circular.period_of(disp_units, period)[0] / (2.0 * np.pi) # radians → display units
def show(rad):
"""A direction in the user's units (axial: halved back to the axis)."""
return float(circular.from_radians(np.mod(rad, turn), disp_units, period))
def lab(rad):
return circular.label(np.mod(rad, turn), units, period)
chart_angles = circular.from_radians(theta, disp_units, period) # what the charts draw
chart_controls = {"units": disp_units if disp_units != "custom" else "radians", "orientation": "compass" if disp_units in ("degrees", "hours") else "math"}
if disp_units == "custom":
chart_angles = theta
# %% Correlation
o_name = "gust_direction"
kind = "circular"
calibration = "approximate"
seed = 42 # shared Wichmann–Hill stream: R draws the same permutations
if kind == "circular":
other = circular.angles(df[o_name] if units in circular.CYCLES else df[o_name].to_numpy(dtype=float), units, period)
other_work = circular.wrap(2.0 * other) if axial else other
else:
other = df[o_name].to_numpy(dtype=float)
other_work = other
# A correlation needs pairs that vary: 2 pairs for two angles, 3 for an angle and a linear variable.
cs.check_rows(len(work), 2 if kind == "circular" else 3, "A circular correlation")
check_not_constant(theta, a_name)
check_not_constant(other, o_name)
r = circular.correlation(work, other_work, kind=kind, calibration=calibration, n_perm=int(9999), seed=seed)
n = len(work)
# %% Assumptions
assumptions = [{"key": "independence", "label": "Independent pairs", "status": "info", "detail": "One pair of values per unit (no repeated readings)."}]
if n < 25 and calibration != "permutation":
warnings.append("Fewer than 25 pairs: the large-sample p-value is approximate; use permutation.")
# %% Result
p = r["p"]
if kind == "circular":
stat, stat_label, symbol = r["r"], "Circular correlation r (Jammalamadaka–SenGupta)", "r"
test_txt = f"z = {r['z']:.3f}"
else:
stat, stat_label, symbol = r["r"], "Circular–linear correlation R (Mardia)", "R"
test_txt = f"nR² = {r['statistic']:.3f} on 2 df"
values = {"n": n, "other_type": kind, "r": r["r"], "p": p, "z": r.get("z"), "r2": r.get("r2"), "statistic": r.get("statistic"),
"r_xc": r.get("r_xc"), "r_xs": r.get("r_xs"), "r_cs": r.get("r_cs"), "p_asymptotic": r.get("p_asymptotic"), "n_perm": r.get("n_perm")}
how = f"permutation ({r['n_perm']} shuffles, seed {seed})" if calibration == "permutation" else "large-sample"
summary = (f"{'Circular' if kind == 'circular' else 'Circular–linear'} correlation between {a_name} and {o_name} (n = {n}): {symbol} = {stat:.3f} "
f"({test_txt}, {cs.fmt_p(p)}). " + ("The two are associated." if p < 0.05 else "No evidence of an association."))
if kind == "linear":
summary += " R is between 0 and 1 and has no sign: it measures how well a sinusoidal pattern in the angle predicts the linear variable."
chart_x = np.asarray(chart_angles)
chart_y = circular.from_radians(other, disp_units, period) if kind == "circular" else other
cs.publish({
"method": "circular.correlation",
"methodVersion": "1.0.1",
"title": "Circular correlation",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"{symbol} = {cs.fmt_num(stat)}, {cs.fmt_p(p)}, n = {n}",
"statistics": [{"key": "r", "label": stat_label, "value": stat}, {"key": "p", "label": "p", "value": p, "format": "p"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"p-value: {how}."],
"values": values,
"charts": [cs.chart("scatter", "scatter", f"{o_name} against {a_name}",
{"x": cs.col(a_name, chart_x[:5000], "numeric"), "y": cs.col(o_name, np.asarray(chart_y)[:5000], "numeric")}, {"fit": "none"})],
})
Jammalamadaka–SenGupta measures whether two angles rise and fall together around their own means. It does have a sign: here 0.92, p < .001.
And an unrelated pair, tested by permutation: −0.14, p = .228.
Use the cycle in a model
ReflectA regression needs numbers on a line, so give it the circle's coordinates: use and as two predictors. That is what Mardia's formula does in miniature.
Which column in your work would you encode this way? And what would happen if you put "hour" into a linear model as a single number, with 23 and 0 as its two extremes?
Check your understanding
CheckpointCheck yourself
You rotate every bearing in a dataset by 90° and rerun Pearson's r on the raw numbers. What happens?
Show the answer
Answer: b
The cut point of the circle was arbitrary, and it decides which values look far apart. Circular correlations are not affected by rotation.
Check yourself
You want to relate hour of day to spend per order. Which is right?
Show the answer
Answer: a
Spend isn't an angle, so this is an angle–linear question.
Check yourself
A measurement has and with an angle whose . What is ?
Show the answer
Answer: 0.5
.
Do it in CodeSplash
In the appIn Analyze, search for "Circular correlation". For a clock-time question, set Angles are in to hours. For encoding in a recipe, Prepare can compute sine and cosine columns.
import numpy as np
import pandas as pd
d = pd.read_csv("ci_wind.csv")
theta = np.radians(d["direction"])
x = d["speed"]
rxc = np.corrcoef(x, np.cos(theta))[0, 1]
rxs = np.corrcoef(x, np.sin(theta))[0, 1]
rcs = np.corrcoef(np.cos(theta), np.sin(theta))[0, 1]
r2 = (rxc ** 2 + rxs ** 2 - 2 * rxc * rxs * rcs) / (1 - rcs ** 2)
print(np.sqrt(r2))d <- read.csv("ci_wind.csv")
theta <- d$direction * pi / 180
x <- d$speed
rxc <- cor(x, cos(theta))
rxs <- cor(x, sin(theta))
rcs <- cor(cos(theta), sin(theta))
r2 <- (rxc^2 + rxs^2 - 2 * rxc * rxs * rcs) / (1 - rcs^2)
sqrt(r2)Recap
Recap- Pearson on raw angles depends on where the circle was cut.
- Use Jammalamadaka–SenGupta for two angles and Mardia's correlation for an angle and a measurement.
- In models, encode a cycle as sine and cosine.