svgcircular-density
Circular density
What shape does the distribution of directions have — one peak, two, or none?
How to read it
- Read distance from the ring as density at that direction.
- Count the humps: one peak, two, or none.
- Compare with the fitted von Mises curve, if on.
- Callout 1: A peak at this time of day.
- Callout 2: Another group's peak.
- Callout 3: Rug: the angles themselves.
Watch out
- A von Mises assumes one peak: two peaks make its mean direction meaningless.
Defaults
- Angles are in
- Hours of the day
- How the column measures direction; the dial is labelled to match.
- Also: Degrees · Radians · Weekday (1 = Mon) · Month (1–12) · Day of year
- Zero and direction
- Top, clockwise (compass, clock)
- Compass bearings and clock times start at the top and run clockwise; mathematical angles start at the right.
- Also: Right, counter-clockwise (maths)
- Kernel concentration ν (0 = automatic)
- 0
- Higher ν = narrower kernel = wigglier curve. Automatic uses Taylor's (2008) rule of thumb.
- Range 0 to 200, step 1
- Fitted von Mises curve
- On
- The von Mises distribution with the sample's mean direction and maximum-likelihood κ.
Pinned in the code
- Density f(θ) = Σ exp(ν cos(θ − θᵢ)) / (2π n I₀(ν)) on 180 points, drawn as radius = base + density; the inner circle is density 0.
- Automatic ν: Taylor (2008) rule of thumb from the von Mises κ̂ of the sample (bounded to [0.5, 500]).
- Fitted curve: von Mises(θ̄, κ̂), κ̂ the exact MLE solving A₁(κ) = R̄ (same algorithm as circular.describe).
# Circular density — Codesplash Chart Lab (recipe "circular-density")
# controls: units=hours, orientation=compass, bandwidth=0, fit=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.special import ive
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("circular-density-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["channel"] = pd.Categorical(df["channel"].astype("string"), categories=["store", "web"])
_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 freq_levels(s, k=8):
"""Declared level order when the column is categorical, else by descending count (ties A→Z)."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(v) for v in s.cat.categories][:k]
vc = s.dropna().astype(str).value_counts()
return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
UNITS, COMPASS = "hours", True # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
PERIOD, ORIGIN = 24, 0 # one full turn, and the value at angle 0
TICK_T = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
TICK_LABELS = ["00:00", "03:00", "06:00", "09:00", "12:00", "15:00", "18:00", "21:00"]
def to_turn(v):
return np.mod((np.asarray(v, dtype=float) - ORIGIN) / PERIOD, 1.0)
def dial(ax):
ax.set_theta_zero_location("N" if COMPASS else "E")
ax.set_theta_direction(-1 if COMPASS else 1)
ax.set_xticks([2 * np.pi * t for t in TICK_T], TICK_LABELS)
ax.grid(True, linewidth=0.5, alpha=0.6)
def circ_stats(t):
C, S = np.cos(2 * np.pi * t).sum(), np.sin(2 * np.pi * t).sum()
n = len(t)
return (np.arctan2(S, C) / (2 * np.pi)) % 1, (np.hypot(C, S) / n if n else np.nan)
def grouped_turns(df, A, G, k):
d = df.dropna(subset=[A])
if not G:
return [("", to_turn(d[A]))]
return [(g, to_turn(d.loc[d[G].astype(str) == g, A])) for g in freq_levels(d[G], k)]
def kappa_mle(r):
if not np.isfinite(r) or r <= 0:
return 0.0
if r >= 1:
return np.inf
k = 2 * r + r**3 + 5 * r**5 / 6 if r < 0.53 else (-0.4 + 1.39 * r + 0.43 / (1 - r) if r < 0.85 else 1 / (r**3 - 4 * r**2 + 3 * r))
for _ in range(200):
a = ive(1, k) / ive(0, k)
slope = 1 - a / k - a * a
if not slope > 0:
break
nxt = k - (a - r) / slope
nxt = k / 2 if nxt <= 0 else nxt
done = abs(nxt - k) < 1e-12 * max(1, k)
k = nxt
if done:
break
return k
def kde_concentration(t):
n = len(t)
k = min(kappa_mle(np.hypot(np.cos(2 * np.pi * t).sum(), np.sin(2 * np.pi * t).sum()) / n if n else np.nan), 50)
if not k > 0 or n < 2:
return 2.0
nu = (3 * n * k * k * ive(2, 2 * k) / ive(0, k) ** 2 / (4 * np.sqrt(np.pi))) ** 0.4 # I2(2k) / I0(k)^2
return float(min(max(nu, 0.5), 500))
def vm_density(grid, mu, kappa):
if not (kappa > 0 and np.isfinite(kappa)):
return np.full_like(grid, 1 / (2 * np.pi))
return np.exp(kappa * (np.cos(2 * np.pi * (grid - mu)) - 1)) / (2 * np.pi * ive(0, kappa))
def circular_kde(t, nu, grid):
s = np.exp(nu * (np.cos(2 * np.pi * (grid[:, None] - t[None, :])) - 1)).sum(axis=1)
return s / (len(t) * 2 * np.pi * ive(0, nu))
A = "hour"
G = "channel"
NU, FIT = 0, True # kernel concentration (0 = automatic); fitted von Mises curve
grid = np.linspace(0, 1, 181)
curves = []
for name, t in grouped_turns(df, A, G, 6):
mu, rbar = circ_stats(t)
kde = circular_kde(t, NU if NU > 0 else kde_concentration(t), grid)
curves.append((name, t, kde, vm_density(grid, mu, kappa_mle(rbar))))
top = max(max(k.max(), f.max() if FIT else 0) for _, _, k, f in curves) or 1
BASE = 0.35 # densities grow outward from the inner circle
radius = lambda dens: BASE + (1 - BASE) * dens / top
fig, ax = plt.subplots(figsize=(6.4, 6.4), subplot_kw={"projection": "polar"})
dial(ax)
theta = 2 * np.pi * grid
ax.plot(theta, np.full_like(theta, BASE), color=GREY, linewidth=0.8)
for i, (name, t, kde, fit) in enumerate(curves):
col = PALETTE[i % len(PALETTE)]
ax.fill_between(theta, BASE, radius(kde), color=col, alpha=0.18, lw=0)
ax.plot(theta, radius(kde), color=col, linewidth=1.6, label=name or "kernel density")
if FIT:
ax.plot(theta, radius(fit), color=col if G else REF, linewidth=1, linestyle="--", label=None if G else "von Mises fit")
ax.vlines(2 * np.pi * t, BASE - 0.05, BASE, color=col, linewidth=0.5, alpha=0.6) # rug
ax.set_ylim(0, 1)
ax.set_yticks([])
ax.legend(fontsize=8, loc="upper right", bbox_to_anchor=(1.2, 1.1))
plt.show()Needs pandas, numpy, matplotlib, scipy · reads circular-density-demo.csv · app theme from the optional codesplash helper
# Circular density — Codesplash Chart Lab (recipe "circular-density")
# controls: units=hours, orientation=compass, bandwidth=0, fit=true
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy.special import ive
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("circular-density-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["channel"] = pd.Categorical(df["channel"].astype("string"), categories=["store", "web"])
_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 freq_levels(s, k=8):
"""Declared level order when the column is categorical, else by descending count (ties A→Z)."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(v) for v in s.cat.categories][:k]
vc = s.dropna().astype(str).value_counts()
return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
UNITS, COMPASS = "hours", True # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
PERIOD, ORIGIN = 24, 0 # one full turn, and the value at angle 0
TICK_T = [0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875]
TICK_LABELS = ["00:00", "03:00", "06:00", "09:00", "12:00", "15:00", "18:00", "21:00"]
def to_turn(v):
return np.mod((np.asarray(v, dtype=float) - ORIGIN) / PERIOD, 1.0)
POLAR = dict(angularaxis=dict(rotation=90 if COMPASS else 0, direction="clockwise" if COMPASS else "counterclockwise",
tickmode="array", tickvals=[360 * t for t in TICK_T], ticktext=TICK_LABELS))
def circ_stats(t):
C, S = np.cos(2 * np.pi * t).sum(), np.sin(2 * np.pi * t).sum()
n = len(t)
return (np.arctan2(S, C) / (2 * np.pi)) % 1, (np.hypot(C, S) / n if n else np.nan)
def grouped_turns(df, A, G, k):
d = df.dropna(subset=[A])
if not G:
return [("", to_turn(d[A]))]
return [(g, to_turn(d.loc[d[G].astype(str) == g, A])) for g in freq_levels(d[G], k)]
def kappa_mle(r):
if not np.isfinite(r) or r <= 0:
return 0.0
if r >= 1:
return np.inf
k = 2 * r + r**3 + 5 * r**5 / 6 if r < 0.53 else (-0.4 + 1.39 * r + 0.43 / (1 - r) if r < 0.85 else 1 / (r**3 - 4 * r**2 + 3 * r))
for _ in range(200):
a = ive(1, k) / ive(0, k)
slope = 1 - a / k - a * a
if not slope > 0:
break
nxt = k - (a - r) / slope
nxt = k / 2 if nxt <= 0 else nxt
done = abs(nxt - k) < 1e-12 * max(1, k)
k = nxt
if done:
break
return k
def kde_concentration(t):
n = len(t)
k = min(kappa_mle(np.hypot(np.cos(2 * np.pi * t).sum(), np.sin(2 * np.pi * t).sum()) / n if n else np.nan), 50)
if not k > 0 or n < 2:
return 2.0
nu = (3 * n * k * k * ive(2, 2 * k) / ive(0, k) ** 2 / (4 * np.sqrt(np.pi))) ** 0.4 # I2(2k) / I0(k)^2
return float(min(max(nu, 0.5), 500))
def vm_density(grid, mu, kappa):
if not (kappa > 0 and np.isfinite(kappa)):
return np.full_like(grid, 1 / (2 * np.pi))
return np.exp(kappa * (np.cos(2 * np.pi * (grid - mu)) - 1)) / (2 * np.pi * ive(0, kappa))
def circular_kde(t, nu, grid):
s = np.exp(nu * (np.cos(2 * np.pi * (grid[:, None] - t[None, :])) - 1)).sum(axis=1)
return s / (len(t) * 2 * np.pi * ive(0, nu))
A = "hour"
G = "channel"
NU, FIT = 0, True
grid = np.linspace(0, 1, 181)
curves = []
for name, t in grouped_turns(df, A, G, 6):
mu, rbar = circ_stats(t)
curves.append((name, t, circular_kde(t, NU if NU > 0 else kde_concentration(t), grid), vm_density(grid, mu, kappa_mle(rbar))))
top = max(max(k.max(), f.max() if FIT else 0) for _, _, k, f in curves) or 1
BASE = 0.35
radius = lambda dens: BASE + (1 - BASE) * dens / top
fig = go.Figure()
fig.add_scatterpolar(r=[BASE] * len(grid), theta=360 * grid, mode="lines", line=dict(color=GREY, width=1), showlegend=False, hoverinfo="skip")
for i, (name, t, kde, fit) in enumerate(curves):
col = PALETTE[i % len(PALETTE)]
fig.add_scatterpolar(r=radius(kde), theta=360 * grid, mode="lines", line=dict(color=col, width=2), name=name or "kernel density")
if FIT:
fig.add_scatterpolar(r=radius(fit), theta=360 * grid, mode="lines", line=dict(color=col if G else REF, width=1, dash="dash"), name=f"von Mises fit {name}".strip())
fig.update_layout(polar=dict(**POLAR, radialaxis=dict(range=[0, 1], showticklabels=False)))
fig.show()Needs pandas, numpy, plotly, scipy · reads circular-density-demo.csv · app theme from the optional codesplash helper
# Circular density — Codesplash Chart Lab (recipe "circular-density")
# controls: units=hours, orientation=compass, bandwidth=0, fit=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("circular-density-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["channel"]] <- factor(df[["channel"]], levels = c("store", "web"))
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
levels_of <- function(v, declared = NULL, k = 8) {
if (!is.null(declared)) return(utils::head(declared, k))
v <- as.character(v[!is.na(v)]); tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
compass <- TRUE # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
period <- 24; origin <- 0 # one full turn, and the value at angle 0 (hours)
tick_t <- c(0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875)
tick_labels <- c("00:00", "03:00", "06:00", "09:00", "12:00", "15:00", "18:00", "21:00")
to_turn <- function(v) ((v - origin) / period) %% 1
dial <- list(coord_polar(start = if (compass) 0 else -pi / 2, direction = if (compass) 1 else -1),
scale_x_continuous(limits = c(0, 1), breaks = tick_t, labels = tick_labels, expand = c(0, 0)))
circ_stats <- function(t) { C <- sum(cos(2 * pi * t)); S <- sum(sin(2 * pi * t))
c(mean = (atan2(S, C) / (2 * pi)) %% 1, rbar = if (length(t)) sqrt(C^2 + S^2) / length(t) else NA) }
grouped_turns <- function(df, a_col, g_col, declared, k) {
d <- df[!is.na(df[[a_col]]), ]
if (is.null(g_col)) return(list(all = to_turn(d[[a_col]])))
lv <- levels_of(d[[g_col]], declared, k)
stats::setNames(lapply(lv, function(g) to_turn(d[[a_col]][!is.na(d[[g_col]]) & as.character(d[[g_col]]) == g])), lv)
}
ive <- function(nu, x) besselI(x, nu, expon.scaled = TRUE)
kappa_mle <- function(r) {
if (!is.finite(r) || r <= 0) return(0)
if (r >= 1) return(Inf)
k <- if (r < 0.53) 2 * r + r^3 + 5 * r^5 / 6 else if (r < 0.85) -0.4 + 1.39 * r + 0.43 / (1 - r) else 1 / (r^3 - 4 * r^2 + 3 * r)
for (i in 1:200) {
a <- ive(1, k) / ive(0, k); slope <- 1 - a / k - a^2
if (!(slope > 0)) break
nxt <- k - (a - r) / slope; if (nxt <= 0) nxt <- k / 2
done <- abs(nxt - k) < 1e-12 * max(1, k); k <- nxt
if (done) break
}
k
}
kde_concentration <- function(t) {
n <- length(t); k <- min(kappa_mle(if (n) sqrt(sum(cos(2 * pi * t))^2 + sum(sin(2 * pi * t))^2) / n else NA), 50)
if (!(k > 0) || n < 2) return(2)
nu <- (3 * n * k^2 * ive(2, 2 * k) / ive(0, k)^2 / (4 * sqrt(pi)))^0.4 # I2(2k) / I0(k)^2
min(max(nu, 0.5), 500)
}
vm_density <- function(grid, mu, kappa) if (!(kappa > 0 && is.finite(kappa))) rep(1 / (2 * pi), length(grid)) else exp(kappa * (cos(2 * pi * (grid - mu)) - 1)) / (2 * pi * ive(0, kappa))
circular_kde <- function(t, nu, grid) rowSums(exp(nu * (cos(2 * pi * outer(grid, t, "-")) - 1))) / (length(t) * 2 * pi * ive(0, nu))
a_col <- "hour"
g_col <- "channel"
nu <- 0; show_fit <- TRUE # kernel concentration (0 = automatic); fitted von Mises curve
groups <- grouped_turns(df, a_col, g_col, c("store", "web"), 6)
grid <- seq(0, 1, length.out = 181)
curves <- do.call(rbind, lapply(names(groups), function(g) { t <- groups[[g]]; s <- circ_stats(t)
data.frame(g = g, x = grid, kde = circular_kde(t, if (nu > 0) nu else kde_concentration(t), grid), fit = vm_density(grid, s[["mean"]], kappa_mle(s[["rbar"]]))) }))
top <- max(curves$kde, if (show_fit) curves$fit else 0)
base <- 0.35 # densities grow outward from the inner circle
curves$r <- base + (1 - base) * curves$kde / top; curves$rf <- base + (1 - base) * curves$fit / top
curves$g <- factor(curves$g, levels = names(groups))
rug <- do.call(rbind, lapply(names(groups), function(g) data.frame(g = g, x = groups[[g]])))
rug$g <- factor(rug$g, levels = names(groups))
p <- ggplot(curves, aes(x, colour = g, fill = g)) + geom_hline(yintercept = base, colour = grey_col) +
geom_ribbon(aes(ymin = base, ymax = r), colour = NA, alpha = 0.18) + geom_line(aes(y = r), linewidth = 0.8) +
{ if (show_fit) geom_line(aes(y = rf), linetype = "dashed", linewidth = 0.5) } +
geom_segment(data = rug, aes(x = x, xend = x, y = base - 0.05, yend = base), inherit.aes = FALSE, colour = ref_col, linewidth = 0.2, alpha = 0.6) +
dial + scale_y_continuous(limits = c(0, 1), breaks = NULL) +
scale_colour_manual(values = cs_cat, guide = if (is.null(g_col)) "none" else "legend") + scale_fill_manual(values = cs_cat, guide = "none") +
labs(x = NULL, y = NULL, colour = g_col) + theme_cs
print(p)Needs ggplot2 · reads circular-density-demo.csv · app theme from the optional codesplashr helper