Directions and cycles
On a circle, 359° and 1° are neighbors and an ordinary mean is wrong. Learn the mean direction, the resultant length and the circular SD.
What runs in CodeSplash
- Circular summary (mean direction, R̄, κ) Verified in Python and R
You will be able to
- Say when a variable is circular and what breaks if you treat it as ordinary
- Compute a mean direction from sines and cosines
- Read R̄ and the circular SD as measures of concentration
The mean that points the wrong way
ReadCompass bearings, clock times, weekdays and seasons are circularCircular dataMeasurements on a loop — compass bearings, clock times, weekdays, months — where the end meets the start.. The scale wraps around: one minute before midnight and one minute after are two minutes apart, not nearly 24 hours.
Average two directions
PredictPredict first
Two birds fly off at bearings of 350° and 10°. Both are nearly due north.
What is their average direction?
Make your guess between 0 and 360 degrees, then reveal.
Reveal
North, 0°. The ordinary mean gives , due south: the one direction neither bird flew.
Add arrows, not numbers
ReadTreat each angle as an arrow of length 1. Add the arrows tip to tail, then see where the sum points:
The direction of that sum is the mean directionMean directionThe direction of the average of the angles as unit vectors, atan2(Σ sin θ, Σ cos θ).. Its length is the mean resultant lengthMean resultant lengthHow tightly angles cluster, from 0 (spread evenly or canceling out) to 1 (all identical).:
near 1 means tight agreement. near 0 means the arrows cancel, either because directions are scattered or because they point in opposite ways.
Move the arrows
ExploreDrag the angles apart and together. Try two tight clusters on opposite sides of the circle, and watch fall while every animal still has a strong preference.
AExplorable · The mean of an angle
What is the average of 350° and 10°?
What does the ordinary arithmetic mean of these angles come to?
Solid arrow: the circular mean, 344.3°, with length R̄ = 0.89. Dashed red: the arithmetic mean, 236.5°, which can point away from every observation.
Commit your prediction above to see the result
Make your prediction to see the result.
Read a summary
Readθ̄ = 84.1°, R̄ = 0.42, κ = 0.92, n = 76
- Mean direction
- 84.101
- Mean resultant length R̄
- 0.4162
- Concentration κ (von Mises)
- 0.9169
- Circular SD
- 75.868
Plots
View data
| heading |
|---|
| 203.20 |
| 97.100 |
| 38.500 |
| 348.40 |
| 157.70 |
| 86.400 |
| 81.800 |
| 140.20 |
| 60.100 |
| 60.800 |
| 48.400 |
| 93 |
| 143 |
| 75.300 |
| 59.700 |
| 139.10 |
| 51.300 |
| 104.20 |
| 59.900 |
| 64.300 |
| 70.300 |
| 71.500 |
| 60.100 |
| 28 |
| 22.500 |
| 118.70 |
| 77.900 |
| 116.30 |
| 349.70 |
| 124.70 |
| 23.200 |
| 33.700 |
| 80.700 |
| 76.300 |
| 75 |
| 70.400 |
| 57.300 |
| 323.40 |
| 46.900 |
| 21.900 |
| 46.400 |
| 28.300 |
| 69.100 |
| 176.50 |
| 53.100 |
| 96.500 |
| 113 |
| 103.80 |
| 125.10 |
| 109.30 |
| 55 |
| 44.300 |
| 65.200 |
| 66 |
| 178.80 |
| 45.400 |
| 68.800 |
| 80 |
| 115.10 |
| 87.300 |
First 60 of 76 rows.
View data
| heading |
|---|
| 203.20 |
| 97.100 |
| 38.500 |
| 348.40 |
| 157.70 |
| 86.400 |
| 81.800 |
| 140.20 |
| 60.100 |
| 60.800 |
| 48.400 |
| 93 |
| 143 |
| 75.300 |
| 59.700 |
| 139.10 |
| 51.300 |
| 104.20 |
| 59.900 |
| 64.300 |
| 70.300 |
| 71.500 |
| 60.100 |
| 28 |
| 22.500 |
| 118.70 |
| 77.900 |
| 116.30 |
| 349.70 |
| 124.70 |
| 23.200 |
| 33.700 |
| 80.700 |
| 76.300 |
| 75 |
| 70.400 |
| 57.300 |
| 323.40 |
| 46.900 |
| 21.900 |
| 46.400 |
| 28.300 |
| 69.100 |
| 176.50 |
| 53.100 |
| 96.500 |
| 113 |
| 103.80 |
| 125.10 |
| 109.30 |
| 55 |
| 44.300 |
| 65.200 |
| 66 |
| 178.80 |
| 45.400 |
| 68.800 |
| 80 |
| 115.10 |
| 87.300 |
First 60 of 76 rows.
Assumptions
- A mean direction exists — Rayleigh Z = 13.16, p < .001: the angles cluster around a direction.
- One preferred direction — R̄ of doubled angles 0.41.
Directions
| Group | n | Mean direction | Mean (degrees) | R̄ | Circular SD (degrees) | κ |
|---|---|---|---|---|---|---|
| All | 76 | 84.1° | 84.101 | 0.4162 | 75.868 | 0.9169 |
- Angles in degrees; interval: normal approximation. κ is the von Mises maximum-likelihood estimate (bias-corrected 0.89).
The exact R script · R R version 4.5.1 (2025-06-13)
# Circular summary (mean direction, R̄, κ)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method circular.describe 1.0.1 · spec 3b1a0ed1fe460219
# Dataset: ci_turtles (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_turtles.parquet", col_select = c("heading")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("heading")]), , 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("heading")) # 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 <- "heading"
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
# %% Summaries
conf <- 0.95
ci_method <- "normal"
seed <- 42 # shared Wichmann-Hill stream: Python draws the same bootstrap samples
d <- cs_circ_describe(theta, conf = conf, axial = axial, ci_method = ci_method, n_boot = 2000, seed = seed)
ray <- cs_circ_rayleigh(work)
n <- d$n
double <- cs_circ_resultant(cs_circ_wrap(2 * theta))$rbar # R̄ of doubled angles: high when the data are axial/bipolar
g_name <- NULL
groups <- list()
if (!is.null(g_name)) {
for (lv in levels(df[[g_name]])) {
sel <- df[[g_name]] == lv
if (sum(sel) == 0) next
dg <- cs_circ_describe(theta[sel], conf = conf, axial = axial, ci_method = "normal")
groups[[length(groups) + 1]] <- list(group = lv, n = sum(sel), mean = show(dg$mean), label = lab(dg$mean), rbar = dg$rbar,
circ_sd = dg$circ_sd * unit_scale, kappa = dg$kappa)
}
}
# %% Assumptions
direction <- if (ray$p >= 0.05) {
list(key = "direction", label = "A mean direction exists", status = "warn", statistic = ray$z, p = ray$p,
detail = sprintf("Rayleigh %s: the angles may be spread uniformly, so the mean direction is not well defined.", cs_fmt_p(ray$p)))
} else {
list(key = "direction", label = "A mean direction exists", status = "pass", statistic = ray$z, p = ray$p,
detail = sprintf("Rayleigh Z = %.2f, %s: the angles cluster around a direction.", ray$z, cs_fmt_p(ray$p)))
}
unimodal <- if (!axial && double > 0.5 && d$rbar < 0.5 * double) {
list(key = "unimodal", label = "One preferred direction", status = "warn",
detail = sprintf("The doubled angles are far more concentrated (R̄ = %.2f vs %.2f): two opposite directions. Treat the data as axial.", double, d$rbar))
} else {
list(key = "unimodal", label = "One preferred direction", status = "pass", detail = sprintf("R̄ of doubled angles %.2f.", double))
}
assumptions <- list(direction, unimodal)
if (n < 10) warnings <- c(warnings, "Fewer than 10 angles; the interval and κ are unstable.")
if (!d$ci_ok) warnings <- c(warnings, "The angles are too dispersed for a normal-approximation interval; use the bootstrap interval or report R̄ only.")
# %% Result
rows <- c(list(list(group = "All", n = n, mean = show(d$mean), label = lab(d$mean), rbar = d$rbar, circ_sd = d$circ_sd * unit_scale, kappa = d$kappa)), groups)
values <- list(
n = n, mean_direction = show(d$mean), mean_direction_rad = d$mean, mean_label = lab(d$mean),
ci_low = if (d$ci_ok) show(d$ci_low) else NULL, ci_high = if (d$ci_ok) show(d$ci_high) else NULL,
rbar = d$rbar, circ_variance = d$variance, circ_sd = d$circ_sd * unit_scale, ang_dev = d$ang_dev * unit_scale,
kappa = d$kappa, kappa_corrected = d$kappa_corrected, se = d$se * unit_scale,
rayleigh_z = ray$z, rayleigh_p = ray$p, rbar_doubled = double, n_groups = length(groups)
)
for (g in groups) {
values[[sprintf("mean_direction[%s]", g$group)]] <- g$mean
values[[sprintf("rbar[%s]", g$group)]] <- g$rbar
values[[sprintf("kappa[%s]", g$group)]] <- g$kappa
values[[sprintf("n[%s]", g$group)]] <- g$n
}
ci_txt <- if (d$ci_ok) sprintf("%.0f%% CI %s to %s", conf * 100, lab(d$ci_low), lab(d$ci_high)) else "no interval (too dispersed)"
how <- if (ci_method == "bootstrap") paste("bootstrap percentile, seed", seed) else "normal approximation"
summary <- paste0(sprintf("Mean direction of %s: %s (%s); mean resultant length R̄ = %.3f, concentration κ = %.2f. ", a_name, lab(d$mean), ci_txt, d$rbar, d$kappa),
if (ray$p < 0.05) "The angles cluster around this direction." else "The angles show no clear preferred direction, so treat the mean with caution.")
take <- seq_len(min(nrow(df), 5000))
chart_roles <- list(angle = cs_col(a_name, chart_angles[take], "numeric"))
if (!is.null(g_name)) chart_roles$group <- cs_col(g_name, as.character(df[[g_name]])[take], levels = levels(df[[g_name]]))
cs_publish(list(
method = "circular.describe",
methodVersion = "1.0.1",
title = "Circular summary",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("θ̄ = %s, R̄ = %s, κ = %s, n = %d", lab(d$mean), cs_fmt_num(d$rbar), cs_fmt_num(d$kappa), n),
statistics = list(
list(key = "mean_direction", label = "Mean direction", value = show(d$mean)),
list(key = "rbar", label = "Mean resultant length R̄", value = d$rbar),
list(key = "kappa", label = "Concentration κ (von Mises)", value = d$kappa),
list(key = "circ_sd", label = "Circular SD", value = d$circ_sd * unit_scale)
),
tables = list(list(
key = "summary", title = "Directions",
columns = list(list(key = "group", label = "Group", type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "label", label = "Mean direction", type = "string"), list(key = "mean", label = sprintf("Mean (%s)", disp_units), type = "number"),
list(key = "rbar", label = "R̄", type = "number"), list(key = "circ_sd", label = sprintf("Circular SD (%s)", disp_units), type = "number"),
list(key = "kappa", label = "κ", type = "number")),
rows = rows
)),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Angles in %s%s; interval: %s. κ is the von Mises maximum-likelihood estimate (bias-corrected %.2f).",
units, if (axial) " (axial: doubled, then halved)" else "", how, d$kappa_corrected)),
values = values,
charts = list(cs_chart("rose", "rose-diagram", paste("Rose diagram of", a_name), chart_roles, chart_controls),
cs_chart("density", "circular-density", paste("Circular density of", a_name), chart_roles, c(chart_controls, list(fit = TRUE))))
))
θ̄ = 84.1°, R̄ = 0.42, κ = 0.92, n = 76
- Mean direction
- 84.101
- Mean resultant length R̄
- 0.4162
- Concentration κ (von Mises)
- 0.9169
- Circular SD
- 75.868
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- A mean direction exists — Rayleigh Z = 13.16, p < .001: the angles cluster around a direction.
- One preferred direction — R̄ of doubled angles 0.41.
Directions
| Group | n | Mean direction | Mean (degrees) | R̄ | Circular SD (degrees) | κ |
|---|---|---|---|---|---|---|
| All | 76 | 84.1° | 84.101 | 0.4162 | 75.868 | 0.9169 |
- Angles in degrees; interval: normal approximation. κ is the von Mises maximum-likelihood estimate (bias-corrected 0.89).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Circular summary (mean direction, R̄, κ)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method circular.describe 1.0.1 · spec 3b1a0ed1fe460219
# Dataset: ci_turtles (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.stats import circular
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ci_turtles.parquet", columns=["heading"])
n_input = len(df)
df = df.dropna(subset=["heading"]) # 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, ["heading"]) # 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 = "heading"
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
# %% Summaries
conf = 0.95
ci_method = "normal"
seed = 42 # shared Wichmann–Hill stream: R draws the same bootstrap samples
d = circular.describe(theta, conf=conf, axial=axial, ci_method=ci_method, n_boot=int(2000), seed=seed)
ray = circular.rayleigh(work)
n = d["n"]
double = circular.resultant(circular.wrap(2.0 * theta))[2] # R̄ of doubled angles: high when the data are axial/bipolar
g_name = None
groups = []
if g_name is not None:
for lv in df[g_name].cat.categories:
sel = (df[g_name] == lv).to_numpy()
if sel.sum() == 0:
continue
dg = circular.describe(theta[sel], conf=conf, axial=axial, ci_method="normal")
groups.append({"group": str(lv), "n": int(sel.sum()), "mean": show(dg["mean"]), "label": lab(dg["mean"]), "rbar": dg["rbar"],
"circ_sd": dg["circ_sd"] * unit_scale, "kappa": dg["kappa"]})
# %% Assumptions
assumptions = []
if ray["p"] >= 0.05:
assumptions.append({"key": "direction", "label": "A mean direction exists", "status": "warn", "statistic": ray["z"], "p": ray["p"],
"detail": f"Rayleigh {cs.fmt_p(ray['p'])}: the angles may be spread uniformly, so the mean direction is not well defined."})
else:
assumptions.append({"key": "direction", "label": "A mean direction exists", "status": "pass", "statistic": ray["z"], "p": ray["p"],
"detail": f"Rayleigh Z = {ray['z']:.2f}, {cs.fmt_p(ray['p'])}: the angles cluster around a direction."})
if not axial and double > 0.5 and d["rbar"] < 0.5 * double:
assumptions.append({"key": "unimodal", "label": "One preferred direction", "status": "warn",
"detail": f"The doubled angles are far more concentrated (R̄ = {double:.2f} vs {d['rbar']:.2f}): two opposite directions. Treat the data as axial."})
else:
assumptions.append({"key": "unimodal", "label": "One preferred direction", "status": "pass", "detail": f"R̄ of doubled angles {double:.2f}."})
if n < 10:
warnings.append("Fewer than 10 angles; the interval and κ are unstable.")
if not d["ci_ok"]:
warnings.append("The angles are too dispersed for a normal-approximation interval; use the bootstrap interval or report R̄ only.")
# %% Result
rows = [{"group": "All", "n": n, "mean": show(d["mean"]), "label": lab(d["mean"]), "rbar": d["rbar"], "circ_sd": d["circ_sd"] * unit_scale, "kappa": d["kappa"]}] + groups
values = {
"n": n, "mean_direction": show(d["mean"]), "mean_direction_rad": d["mean"], "mean_label": lab(d["mean"]),
"ci_low": show(d["ci_low"]) if d["ci_ok"] else None, "ci_high": show(d["ci_high"]) if d["ci_ok"] else None,
"rbar": d["rbar"], "circ_variance": d["variance"], "circ_sd": d["circ_sd"] * unit_scale, "ang_dev": d["ang_dev"] * unit_scale,
"kappa": d["kappa"], "kappa_corrected": d["kappa_corrected"], "se": d["se"] * unit_scale,
"rayleigh_z": ray["z"], "rayleigh_p": ray["p"], "rbar_doubled": double, "n_groups": len(groups),
}
for g in groups:
values[f"mean_direction[{g['group']}]"] = g["mean"]
values[f"rbar[{g['group']}]"] = g["rbar"]
values[f"kappa[{g['group']}]"] = g["kappa"]
values[f"n[{g['group']}]"] = g["n"]
ci_txt = (f"{conf:.0%} CI {lab(d['ci_low'])} to {lab(d['ci_high'])}" if d["ci_ok"] else "no interval (too dispersed)")
how = "bootstrap percentile, seed " + str(seed) if ci_method == "bootstrap" else "normal approximation"
summary = (f"Mean direction of {a_name}: {lab(d['mean'])} ({ci_txt}); mean resultant length R̄ = {d['rbar']:.3f}, "
f"concentration κ = {d['kappa']:.2f}. " + ("The angles cluster around this direction." if ray["p"] < 0.05 else "The angles show no clear preferred direction, so treat the mean with caution."))
chart_roles = {"angle": cs.col(a_name, np.asarray(chart_angles)[:5000], "numeric")}
if g_name is not None:
chart_roles["group"] = cs.col(g_name, df[g_name].astype(str).to_numpy()[:5000], levels=[str(x) for x in df[g_name].cat.categories])
cs.publish({
"method": "circular.describe",
"methodVersion": "1.0.1",
"title": "Circular summary",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"θ̄ = {lab(d['mean'])}, R̄ = {cs.fmt_num(d['rbar'])}, κ = {cs.fmt_num(d['kappa'])}, n = {n}",
"statistics": [
{"key": "mean_direction", "label": "Mean direction", "value": show(d["mean"])},
{"key": "rbar", "label": "Mean resultant length R̄", "value": d["rbar"]},
{"key": "kappa", "label": "Concentration κ (von Mises)", "value": d["kappa"]},
{"key": "circ_sd", "label": "Circular SD", "value": d["circ_sd"] * unit_scale},
],
"tables": [{
"key": "summary", "title": "Directions",
"columns": [{"key": "group", "label": "Group", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "label", "label": "Mean direction", "type": "string"}, {"key": "mean", "label": f"Mean ({disp_units})", "type": "number"},
{"key": "rbar", "label": "R̄", "type": "number"}, {"key": "circ_sd", "label": f"Circular SD ({disp_units})", "type": "number"},
{"key": "kappa", "label": "κ", "type": "number"}],
"rows": rows,
}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Angles in {units}{' (axial: doubled, then halved)' if axial else ''}; interval: {how}. κ is the von Mises maximum-likelihood estimate (bias-corrected {d['kappa_corrected']:.2f})."],
"values": values,
"charts": [cs.chart("rose", "rose-diagram", f"Rose diagram of {a_name}", chart_roles, chart_controls),
cs.chart("density", "circular-density", f"Circular density of {a_name}", chart_roles, {**chart_controls, "fit": True})],
})
For 76 simulated turtle headings:
- Mean direction 84.1°, 95% CI 65.5 to 102.7.
- = 0.42.
- Circular SDCircular standard deviationSpread of angles, √(−2 ln R̄), reported in the data's units (degrees, hours). = 75.9 degrees.
The circular SD is in radians. It stretches without limit as approaches 0, so don't read it as a spread in the ordinary sense when is small.
Clock times work the same way
ReadChoose the cycle under Angles are in. For times of day, CodeSplash turns a full day into a full turn and reports the answer back as a time.
In a simulated table, web and store orders together have a mean time of 16:36. Store orders center around midday and web orders in the evening, so that overall mean describes neither channel. Read each group's own row on the card.
θ̄ = 16:36, R̄ = 0.39, κ = 0.85, n = 300
- Mean direction
- 16.607
- Mean resultant length R̄
- 0.3896
- Concentration κ (von Mises)
- 0.8472
- Circular SD
- 5.244
Plots
View data
| hour | channel |
|---|---|
| 10.498 | store |
| 18.395 | web |
| 20.048 | web |
| 11.985 | store |
| 19.361 | web |
| 18.519 | web |
| 12.777 | store |
| 22.198 | web |
| 10.546 | store |
| 9.366 | store |
| 20.269 | web |
| 19.236 | web |
| 10.476 | store |
| 12.035 | store |
| 12.550 | store |
| 18.450 | web |
| 10.687 | store |
| 21.640 | web |
| 15.376 | store |
| 21.986 | web |
| 17.463 | web |
| 14.976 | store |
| 20.936 | web |
| 13.225 | store |
| 18.181 | web |
| 16.543 | web |
| 22.579 | web |
| 23.692 | web |
| 14.532 | web |
| 11.943 | store |
| 20.543 | web |
| 17.847 | web |
| 22.978 | web |
| 15.664 | web |
| 23.667 | web |
| 20.776 | web |
| 14.455 | store |
| 12.651 | store |
| 13.586 | store |
| 21.875 | web |
| 18.900 | store |
| 23.229 | web |
| 20.853 | web |
| 16.826 | web |
| 15.308 | web |
| 17.155 | web |
| 20.045 | web |
| 13.359 | store |
| 3.332 | web |
| 23.565 | web |
| 11.042 | store |
| 23.398 | web |
| 17.720 | web |
| 9.948 | store |
| 14.957 | store |
| 23.017 | web |
| 22.943 | web |
| 20.799 | web |
| 10.847 | store |
| 13.674 | store |
First 60 of 300 rows.
View data
| hour | channel |
|---|---|
| 10.498 | store |
| 18.395 | web |
| 20.048 | web |
| 11.985 | store |
| 19.361 | web |
| 18.519 | web |
| 12.777 | store |
| 22.198 | web |
| 10.546 | store |
| 9.366 | store |
| 20.269 | web |
| 19.236 | web |
| 10.476 | store |
| 12.035 | store |
| 12.550 | store |
| 18.450 | web |
| 10.687 | store |
| 21.640 | web |
| 15.376 | store |
| 21.986 | web |
| 17.463 | web |
| 14.976 | store |
| 20.936 | web |
| 13.225 | store |
| 18.181 | web |
| 16.543 | web |
| 22.579 | web |
| 23.692 | web |
| 14.532 | web |
| 11.943 | store |
| 20.543 | web |
| 17.847 | web |
| 22.978 | web |
| 15.664 | web |
| 23.667 | web |
| 20.776 | web |
| 14.455 | store |
| 12.651 | store |
| 13.586 | store |
| 21.875 | web |
| 18.900 | store |
| 23.229 | web |
| 20.853 | web |
| 16.826 | web |
| 15.308 | web |
| 17.155 | web |
| 20.045 | web |
| 13.359 | store |
| 3.332 | web |
| 23.565 | web |
| 11.042 | store |
| 23.398 | web |
| 17.720 | web |
| 9.948 | store |
| 14.957 | store |
| 23.017 | web |
| 22.943 | web |
| 20.799 | web |
| 10.847 | store |
| 13.674 | store |
First 60 of 300 rows.
Assumptions
- A mean direction exists — Rayleigh Z = 45.55, p < .001: the angles cluster around a direction.
- One preferred direction — R̄ of doubled angles 0.19.
Directions
| Group | n | Mean direction | Mean (hours) | R̄ | Circular SD (hours) | κ |
|---|---|---|---|---|---|---|
| All | 300 | 16:36 | 16.607 | 0.3896 | 5.244 | 0.8472 |
| store | 128 | 12:18 | 12.303 | 0.8353 | 2.292 | 3.392 |
| web | 172 | 20:11 | 20.186 | 0.6966 | 3.248 | 1.993 |
- Angles in hours; interval: normal approximation. κ is the von Mises maximum-likelihood estimate (bias-corrected 0.84).
The exact R script · R R version 4.5.1 (2025-06-13)
# Circular summary (mean direction, R̄, κ)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method circular.describe 1.0.1 · spec 457bfb0e83f303a5
# Dataset: ci_hours (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_hours.parquet", col_select = c("hour", "channel")))
n_input <- nrow(df)
df[["channel"]] <- factor(df[["channel"]], levels = c("store", "web")) # stored level order
df <- df[stats::complete.cases(df[c("hour", "channel")]), , 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("hour", "channel")) # 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 <- "hours"
period <- NULL
disp_units <- switch(units, time_of_day = "hours", day_of_week = "weekday", day_of_year = "doy", units)
axial <- FALSE
a_name <- "hour"
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
# %% Summaries
conf <- 0.95
ci_method <- "normal"
seed <- 42 # shared Wichmann-Hill stream: Python draws the same bootstrap samples
d <- cs_circ_describe(theta, conf = conf, axial = axial, ci_method = ci_method, n_boot = 2000, seed = seed)
ray <- cs_circ_rayleigh(work)
n <- d$n
double <- cs_circ_resultant(cs_circ_wrap(2 * theta))$rbar # R̄ of doubled angles: high when the data are axial/bipolar
g_name <- "channel"
groups <- list()
if (!is.null(g_name)) {
for (lv in levels(df[[g_name]])) {
sel <- df[[g_name]] == lv
if (sum(sel) == 0) next
dg <- cs_circ_describe(theta[sel], conf = conf, axial = axial, ci_method = "normal")
groups[[length(groups) + 1]] <- list(group = lv, n = sum(sel), mean = show(dg$mean), label = lab(dg$mean), rbar = dg$rbar,
circ_sd = dg$circ_sd * unit_scale, kappa = dg$kappa)
}
}
# %% Assumptions
direction <- if (ray$p >= 0.05) {
list(key = "direction", label = "A mean direction exists", status = "warn", statistic = ray$z, p = ray$p,
detail = sprintf("Rayleigh %s: the angles may be spread uniformly, so the mean direction is not well defined.", cs_fmt_p(ray$p)))
} else {
list(key = "direction", label = "A mean direction exists", status = "pass", statistic = ray$z, p = ray$p,
detail = sprintf("Rayleigh Z = %.2f, %s: the angles cluster around a direction.", ray$z, cs_fmt_p(ray$p)))
}
unimodal <- if (!axial && double > 0.5 && d$rbar < 0.5 * double) {
list(key = "unimodal", label = "One preferred direction", status = "warn",
detail = sprintf("The doubled angles are far more concentrated (R̄ = %.2f vs %.2f): two opposite directions. Treat the data as axial.", double, d$rbar))
} else {
list(key = "unimodal", label = "One preferred direction", status = "pass", detail = sprintf("R̄ of doubled angles %.2f.", double))
}
assumptions <- list(direction, unimodal)
if (n < 10) warnings <- c(warnings, "Fewer than 10 angles; the interval and κ are unstable.")
if (!d$ci_ok) warnings <- c(warnings, "The angles are too dispersed for a normal-approximation interval; use the bootstrap interval or report R̄ only.")
# %% Result
rows <- c(list(list(group = "All", n = n, mean = show(d$mean), label = lab(d$mean), rbar = d$rbar, circ_sd = d$circ_sd * unit_scale, kappa = d$kappa)), groups)
values <- list(
n = n, mean_direction = show(d$mean), mean_direction_rad = d$mean, mean_label = lab(d$mean),
ci_low = if (d$ci_ok) show(d$ci_low) else NULL, ci_high = if (d$ci_ok) show(d$ci_high) else NULL,
rbar = d$rbar, circ_variance = d$variance, circ_sd = d$circ_sd * unit_scale, ang_dev = d$ang_dev * unit_scale,
kappa = d$kappa, kappa_corrected = d$kappa_corrected, se = d$se * unit_scale,
rayleigh_z = ray$z, rayleigh_p = ray$p, rbar_doubled = double, n_groups = length(groups)
)
for (g in groups) {
values[[sprintf("mean_direction[%s]", g$group)]] <- g$mean
values[[sprintf("rbar[%s]", g$group)]] <- g$rbar
values[[sprintf("kappa[%s]", g$group)]] <- g$kappa
values[[sprintf("n[%s]", g$group)]] <- g$n
}
ci_txt <- if (d$ci_ok) sprintf("%.0f%% CI %s to %s", conf * 100, lab(d$ci_low), lab(d$ci_high)) else "no interval (too dispersed)"
how <- if (ci_method == "bootstrap") paste("bootstrap percentile, seed", seed) else "normal approximation"
summary <- paste0(sprintf("Mean direction of %s: %s (%s); mean resultant length R̄ = %.3f, concentration κ = %.2f. ", a_name, lab(d$mean), ci_txt, d$rbar, d$kappa),
if (ray$p < 0.05) "The angles cluster around this direction." else "The angles show no clear preferred direction, so treat the mean with caution.")
take <- seq_len(min(nrow(df), 5000))
chart_roles <- list(angle = cs_col(a_name, chart_angles[take], "numeric"))
if (!is.null(g_name)) chart_roles$group <- cs_col(g_name, as.character(df[[g_name]])[take], levels = levels(df[[g_name]]))
cs_publish(list(
method = "circular.describe",
methodVersion = "1.0.1",
title = "Circular summary",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("θ̄ = %s, R̄ = %s, κ = %s, n = %d", lab(d$mean), cs_fmt_num(d$rbar), cs_fmt_num(d$kappa), n),
statistics = list(
list(key = "mean_direction", label = "Mean direction", value = show(d$mean)),
list(key = "rbar", label = "Mean resultant length R̄", value = d$rbar),
list(key = "kappa", label = "Concentration κ (von Mises)", value = d$kappa),
list(key = "circ_sd", label = "Circular SD", value = d$circ_sd * unit_scale)
),
tables = list(list(
key = "summary", title = "Directions",
columns = list(list(key = "group", label = "Group", type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "label", label = "Mean direction", type = "string"), list(key = "mean", label = sprintf("Mean (%s)", disp_units), type = "number"),
list(key = "rbar", label = "R̄", type = "number"), list(key = "circ_sd", label = sprintf("Circular SD (%s)", disp_units), type = "number"),
list(key = "kappa", label = "κ", type = "number")),
rows = rows
)),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Angles in %s%s; interval: %s. κ is the von Mises maximum-likelihood estimate (bias-corrected %.2f).",
units, if (axial) " (axial: doubled, then halved)" else "", how, d$kappa_corrected)),
values = values,
charts = list(cs_chart("rose", "rose-diagram", paste("Rose diagram of", a_name), chart_roles, chart_controls),
cs_chart("density", "circular-density", paste("Circular density of", a_name), chart_roles, c(chart_controls, list(fit = TRUE))))
))
θ̄ = 16:36, R̄ = 0.39, κ = 0.85, n = 300
- Mean direction
- 16.607
- Mean resultant length R̄
- 0.3896
- Concentration κ (von Mises)
- 0.8472
- Circular SD
- 5.244
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- A mean direction exists — Rayleigh Z = 45.55, p < .001: the angles cluster around a direction.
- One preferred direction — R̄ of doubled angles 0.19.
Directions
| Group | n | Mean direction | Mean (hours) | R̄ | Circular SD (hours) | κ |
|---|---|---|---|---|---|---|
| All | 300 | 16:36 | 16.607 | 0.3896 | 5.244 | 0.8472 |
| store | 128 | 12:18 | 12.303 | 0.8353 | 2.292 | 3.392 |
| web | 172 | 20:11 | 20.186 | 0.6966 | 3.248 | 1.993 |
- Angles in hours; interval: normal approximation. κ is the von Mises maximum-likelihood estimate (bias-corrected 0.84).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Circular summary (mean direction, R̄, κ)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method circular.describe 1.0.1 · spec 457bfb0e83f303a5
# Dataset: ci_hours (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.stats import circular
# %% Data
df = pd.read_parquet("tests/parity/fixtures/ci_hours.parquet", columns=["hour", "channel"])
n_input = len(df)
df["channel"] = pd.Categorical(df["channel"], categories=["store", "web"]) # stored level order
df = df.dropna(subset=["hour", "channel"]) # listwise deletion over the analysis columns
df["channel"] = df["channel"].cat.remove_unused_categories()
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, ["hour", "channel"]) # 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 = "hours"
period = None
disp_units = {"time_of_day": "hours", "day_of_week": "weekday", "day_of_year": "doy"}.get(units, units)
axial = False
a_name = "hour"
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
# %% Summaries
conf = 0.95
ci_method = "normal"
seed = 42 # shared Wichmann–Hill stream: R draws the same bootstrap samples
d = circular.describe(theta, conf=conf, axial=axial, ci_method=ci_method, n_boot=int(2000), seed=seed)
ray = circular.rayleigh(work)
n = d["n"]
double = circular.resultant(circular.wrap(2.0 * theta))[2] # R̄ of doubled angles: high when the data are axial/bipolar
g_name = "channel"
groups = []
if g_name is not None:
for lv in df[g_name].cat.categories:
sel = (df[g_name] == lv).to_numpy()
if sel.sum() == 0:
continue
dg = circular.describe(theta[sel], conf=conf, axial=axial, ci_method="normal")
groups.append({"group": str(lv), "n": int(sel.sum()), "mean": show(dg["mean"]), "label": lab(dg["mean"]), "rbar": dg["rbar"],
"circ_sd": dg["circ_sd"] * unit_scale, "kappa": dg["kappa"]})
# %% Assumptions
assumptions = []
if ray["p"] >= 0.05:
assumptions.append({"key": "direction", "label": "A mean direction exists", "status": "warn", "statistic": ray["z"], "p": ray["p"],
"detail": f"Rayleigh {cs.fmt_p(ray['p'])}: the angles may be spread uniformly, so the mean direction is not well defined."})
else:
assumptions.append({"key": "direction", "label": "A mean direction exists", "status": "pass", "statistic": ray["z"], "p": ray["p"],
"detail": f"Rayleigh Z = {ray['z']:.2f}, {cs.fmt_p(ray['p'])}: the angles cluster around a direction."})
if not axial and double > 0.5 and d["rbar"] < 0.5 * double:
assumptions.append({"key": "unimodal", "label": "One preferred direction", "status": "warn",
"detail": f"The doubled angles are far more concentrated (R̄ = {double:.2f} vs {d['rbar']:.2f}): two opposite directions. Treat the data as axial."})
else:
assumptions.append({"key": "unimodal", "label": "One preferred direction", "status": "pass", "detail": f"R̄ of doubled angles {double:.2f}."})
if n < 10:
warnings.append("Fewer than 10 angles; the interval and κ are unstable.")
if not d["ci_ok"]:
warnings.append("The angles are too dispersed for a normal-approximation interval; use the bootstrap interval or report R̄ only.")
# %% Result
rows = [{"group": "All", "n": n, "mean": show(d["mean"]), "label": lab(d["mean"]), "rbar": d["rbar"], "circ_sd": d["circ_sd"] * unit_scale, "kappa": d["kappa"]}] + groups
values = {
"n": n, "mean_direction": show(d["mean"]), "mean_direction_rad": d["mean"], "mean_label": lab(d["mean"]),
"ci_low": show(d["ci_low"]) if d["ci_ok"] else None, "ci_high": show(d["ci_high"]) if d["ci_ok"] else None,
"rbar": d["rbar"], "circ_variance": d["variance"], "circ_sd": d["circ_sd"] * unit_scale, "ang_dev": d["ang_dev"] * unit_scale,
"kappa": d["kappa"], "kappa_corrected": d["kappa_corrected"], "se": d["se"] * unit_scale,
"rayleigh_z": ray["z"], "rayleigh_p": ray["p"], "rbar_doubled": double, "n_groups": len(groups),
}
for g in groups:
values[f"mean_direction[{g['group']}]"] = g["mean"]
values[f"rbar[{g['group']}]"] = g["rbar"]
values[f"kappa[{g['group']}]"] = g["kappa"]
values[f"n[{g['group']}]"] = g["n"]
ci_txt = (f"{conf:.0%} CI {lab(d['ci_low'])} to {lab(d['ci_high'])}" if d["ci_ok"] else "no interval (too dispersed)")
how = "bootstrap percentile, seed " + str(seed) if ci_method == "bootstrap" else "normal approximation"
summary = (f"Mean direction of {a_name}: {lab(d['mean'])} ({ci_txt}); mean resultant length R̄ = {d['rbar']:.3f}, "
f"concentration κ = {d['kappa']:.2f}. " + ("The angles cluster around this direction." if ray["p"] < 0.05 else "The angles show no clear preferred direction, so treat the mean with caution."))
chart_roles = {"angle": cs.col(a_name, np.asarray(chart_angles)[:5000], "numeric")}
if g_name is not None:
chart_roles["group"] = cs.col(g_name, df[g_name].astype(str).to_numpy()[:5000], levels=[str(x) for x in df[g_name].cat.categories])
cs.publish({
"method": "circular.describe",
"methodVersion": "1.0.1",
"title": "Circular summary",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"θ̄ = {lab(d['mean'])}, R̄ = {cs.fmt_num(d['rbar'])}, κ = {cs.fmt_num(d['kappa'])}, n = {n}",
"statistics": [
{"key": "mean_direction", "label": "Mean direction", "value": show(d["mean"])},
{"key": "rbar", "label": "Mean resultant length R̄", "value": d["rbar"]},
{"key": "kappa", "label": "Concentration κ (von Mises)", "value": d["kappa"]},
{"key": "circ_sd", "label": "Circular SD", "value": d["circ_sd"] * unit_scale},
],
"tables": [{
"key": "summary", "title": "Directions",
"columns": [{"key": "group", "label": "Group", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "label", "label": "Mean direction", "type": "string"}, {"key": "mean", "label": f"Mean ({disp_units})", "type": "number"},
{"key": "rbar", "label": "R̄", "type": "number"}, {"key": "circ_sd", "label": f"Circular SD ({disp_units})", "type": "number"},
{"key": "kappa", "label": "κ", "type": "number"}],
"rows": rows,
}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Angles in {units}{' (axial: doubled, then halved)' if axial else ''}; interval: {how}. κ is the von Mises maximum-likelihood estimate (bias-corrected {d['kappa_corrected']:.2f})."],
"values": values,
"charts": [cs.chart("rose", "rose-diagram", f"Rose diagram of {a_name}", chart_roles, chart_controls),
cs.chart("density", "circular-density", f"Circular density of {a_name}", chart_roles, {**chart_controls, "fit": True})],
})
You can also point it at a date-time column, using Time of day, Day and time of the week or Time of year.
Where is your cycle?
ReflectLook at one dataset you work with. Which column is secretly circular? Hour of day, month, day of week, wind direction, phase of a process.
What would an ordinary mean or an ordinary correlation with that column get wrong?
Check your understanding
CheckpointCheck yourself
Why does an ordinary mean fail for hours of the day?
Show the answer
Answer: b
23 and 01 average to 12 on a straight line, though they are two hours apart around midnight.
Check yourself
A sample has . Which conclusion is safe?
Show the answer
Answer: c
A small resultant length has more than one cause. Look at a rose diagram before you interpret it.
Check yourself
Three arrows point at 0°, 90° and 180°. What is their mean direction, in degrees?
Show the answer
Answer: 90
The sines add to and the cosines to . So the sum points straight up: 90°.
Do it in CodeSplash
In the appIn Analyze, search for "circular summary". Set Angles are in to match your column. The chart defaults to a rose diagram.
import numpy as np
import pandas as pd
theta = np.radians(pd.read_csv("ci_turtles.csv")["heading"])
C, S = np.cos(theta).mean(), np.sin(theta).mean()
mean_dir = np.degrees(np.arctan2(S, C)) % 360
rbar = np.hypot(C, S)
circ_sd = np.degrees(np.sqrt(-2 * np.log(rbar)))
print(mean_dir, rbar, circ_sd)theta <- read.csv("ci_turtles.csv")$heading * pi / 180
C <- mean(cos(theta)); S <- mean(sin(theta))
mean_dir <- (atan2(S, C) * 180 / pi) %% 360
rbar <- sqrt(C^2 + S^2)
circ_sd <- sqrt(-2 * log(rbar)) * 180 / pi
c(mean_dir, rbar, circ_sd)Recap
Recap- When a scale wraps around, average the arrows, not the numbers.
- The sum's direction is the mean direction; its length measures concentration.
- A small does not prove there is no pattern. Plot first.
Concepts in this lesson