Skip to content
svgcircular-density

Circular density

What shape does the distribution of directions have — one peak, two, or none?

Demo data · seed 20261101 · 600 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read distance from the ring as density at that direction.
  2. Count the humps: one peak, two, or none.
  3. Compare with the fitted von Mises curve, if on.
  1. Callout 1: A peak at this time of day.
  2. Callout 2: Another group's peak.
  3. 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