Skip to content

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.

Advanced ~11 min8 steps

What runs in CodeSplash

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

01

Wrapping breaks Pearson

Read

Pearson'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.
02

Does direction predict speed?

Predict

Predict 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?

Close to zeroModerateStrong
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.

03

How it's built

Read

Correlate the measurement xx with cos⁡θ\cos\theta and with sin⁡θ\sin\theta, and combine them, allowing for the correlation between the two:

R2=rxc2+rxs2−2 rxc rxs rcs1−rcs2R^2 = \frac{r_{xc}^2 + r_{xs}^2 - 2\,r_{xc}\,r_{xs}\,r_{cs}}{1 - r_{cs}^2}

Here, rxcr_{xc} = 0.04 and rxsr_{xs} = −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.

04

Two angles together

Read
Circular correlationRecorded · Python and R agreeRecorded 2026-11-17 · 12 values compared
R

r = 0.92, p < .001, n = 240

Circular correlation r (Jammalamadaka–SenGupta)
0.9153
p
< .001

Plots

gust_direction against directionHow do two numeric variables move together?
View data
directiongust_direction
182.70175
228.50249.40
313.40285.70
353.10353.40
308.70340.10
249.60269.70
242.20258.30
281295.20
231197.20
158.10177.90
344.3031.100
247.60243.60
231.50241.80
284.20310.90
234.50266
328.40342.50
308.50347.90
190.40188.10
318.70269.90
332.70333.80
245.70256.70
277.20244.40
251267.60
302303.10
306.60309.30
184.50171.30
183.20197
333323.40
345.4012.500
231.50234.90
213.20207.60
269.10295.90
222.90229.80
273.30239.20
189.50194.20
252.50236.90
212.80217.30
228.10226.20
228.60229.20
271.90256.20
273.80237.70
242.80264.20
45.70059.300
205.10204.50
297.90332.20
281265.10
281.10257.60
351.20334.30
286300.40
258.30246.70
221.60223.80
230.60245.70
257.50261.60
283.40267.30
293.50294.20
221.40228.60
313.50332.40
254.90260.80
269.30292
302.30259.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")))
))
Python

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.

05

Use the cycle in a model

Reflect

A regression needs numbers on a line, so give it the circle's coordinates: use sin⁡θ\sin\theta and cos⁡θ\cos\theta 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?

06

Check your understanding

Checkpoint

Check 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 rxc=0.5r_{xc} = 0.5 and rxs=0.5r_{xs} = 0.5 with an angle whose rcs=0r_{cs} = 0. What is R2R^2?

Show the answer

Answer: 0.5

(0.25+0.25−0)/(1−0)=0.5(0.25 + 0.25 - 0)/(1 - 0) = 0.5.

07

Do it in CodeSplash

In the app

In 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.

Python
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))
R
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)
08

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.