svgcircular-dot
Circular dot plot
Where does each individual angle fall, and how do groups compare?
How to read it
- Read each dot as one angle, stacked outward from its ring.
- Each ring is one group.
- Read inner arrows as group mean directions.
- Callout 1: A group's dots: clustered around this direction.
- Callout 2: Mean direction arrow.
- Callout 3: A ring per group.
Watch out
- Don't compute a usual mean on angles: the mean of 350° and 10° is 0°, not 180°.
Defaults
- Angles are in
- Degrees
- How the column measures direction; the dial is labelled to match.
- Also: Radians · Hours of the day · 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)
- Stacking resolution (sectors)
- 72
- How finely angles are binned before stacking.
- Range 12 to 360, step 6
Pinned in the code
- Each angle is placed at the centre of its sector (resolution 360/k) and stacked outward; nothing is smoothed.
- One ring per group, inner to outer in level order; inner arrows: mean direction and R̄ per group (scaled to the inner disc).
# Circular dot plot — Codesplash Chart Lab (recipe "circular-dot")
# controls: units=degrees, orientation=compass, bins=72
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]
df = pd.read_csv("circular-dot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["group"] = pd.Categorical(df["group"].astype("string"), categories=["control", "magnet", "anosmic"])
_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 = "degrees", True # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
PERIOD, ORIGIN = 360, 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 = ["0°", "45°", "90°", "135°", "180°", "225°", "270°", "315°"]
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)]
A = "bearing"
G = "group"
BINS = 72 # stacking resolution (sectors)
groups = grouped_turns(df, A, G, 6)
gap = 0.55 / len(groups) # one ring per group, inner to outer
stacked = []
for i, (name, t) in enumerate(groups):
b = np.minimum(BINS - 1, np.floor(t * BINS).astype(int))
level = pd.Series(b).groupby(b).cumcount().to_numpy() # dots stack outward in their sector
stacked.append(((b + 0.5) / BINS, level))
max_level = max([lv.max() + 1 for _, lv in stacked if len(lv)] or [1])
step = min(0.024, gap * 0.9 / max_level, 2 * np.pi * 0.45 / BINS)
fig, ax = plt.subplots(figsize=(6.4, 6.4), subplot_kw={"projection": "polar"})
dial(ax)
ring = np.linspace(0, 2 * np.pi, 361)
for i, ((name, t), (tc, level)) in enumerate(zip(groups, stacked)):
base = 0.4 + i * gap
col = PALETTE[i % len(PALETTE)] if G else REF
ax.plot(ring, np.full_like(ring, base), color=GREY, linewidth=0.8)
ax.scatter(2 * np.pi * tc, base + 0.42 * step + level * step, s=12, color=col, marker=SERIES_MARKERS[i % 8] if G else "o", label=name or None, zorder=3) # shape per group, as in the app
mu, rbar = circ_stats(t) # inner arrows: mean direction and R̄, scaled to the inner disc
ax.annotate("", xy=(2 * np.pi * mu, 0.36 * rbar), xytext=(0, 0), arrowprops=dict(arrowstyle="-|>", color=col, lw=1.6, linestyle=SERIES_DASHES[i % 8] if G else "-"))
ax.set_ylim(0, 1)
ax.set_yticks([])
if G:
ax.legend(fontsize=8, loc="upper right", bbox_to_anchor=(1.18, 1.1))
plt.show()Needs pandas, numpy, matplotlib · reads circular-dot-demo.csv · app theme from the optional codesplash helper
# Circular dot plot — Codesplash Chart Lab (recipe "circular-dot")
# controls: units=degrees, orientation=compass, bins=72
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
df = pd.read_csv("circular-dot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["group"] = pd.Categorical(df["group"].astype("string"), categories=["control", "magnet", "anosmic"])
_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 = "degrees", True # compass: 0 at the top, clockwise; else 0 at the right, counter-clockwise
PERIOD, ORIGIN = 360, 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 = ["0°", "45°", "90°", "135°", "180°", "225°", "270°", "315°"]
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)]
A = "bearing"
G = "group"
BINS = 72
groups = grouped_turns(df, A, G, 6)
gap = 0.55 / len(groups)
stacked = []
for name, t in groups:
b = np.minimum(BINS - 1, np.floor(t * BINS).astype(int))
stacked.append(((b + 0.5) / BINS, pd.Series(b).groupby(b).cumcount().to_numpy()))
max_level = max([lv.max() + 1 for _, lv in stacked if len(lv)] or [1])
step = min(0.024, gap * 0.9 / max_level, 2 * np.pi * 0.45 / BINS)
fig = go.Figure()
for i, ((name, t), (tc, level)) in enumerate(zip(groups, stacked)):
base = 0.4 + i * gap
col = PALETTE[i % len(PALETTE)] if G else REF
fig.add_scatterpolar(r=[base] * 361, theta=np.linspace(0, 360, 361), mode="lines", line=dict(color=GREY, width=1), showlegend=False, hoverinfo="skip")
fig.add_scatterpolar(r=base + 0.42 * step + level * step, theta=360 * tc, mode="markers", marker=dict(color=col, size=6, symbol=SERIES_MARKERS[i % 8] if G else "circle"), name=name or A) # shape per group
mu, rbar = circ_stats(t)
fig.add_scatterpolar(r=[0, 0.36 * rbar], theta=[360 * mu] * 2, mode="lines", line=dict(color=col, width=2, dash=SERIES_DASHES[i % 8] if G else "solid"), showlegend=False)
fig.update_layout(polar=dict(**POLAR, radialaxis=dict(range=[0, 1], showticklabels=False)), showlegend=bool(G))
fig.show()Needs pandas, numpy, plotly · reads circular-dot-demo.csv · app theme from the optional codesplash helper
# Circular dot plot — Codesplash Chart Lab (recipe "circular-dot")
# controls: units=degrees, orientation=compass, bins=72
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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("circular-dot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["group"]] <- factor(df[["group"]], levels = c("control", "magnet", "anosmic"))
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 <- 360; origin <- 0 # one full turn, and the value at angle 0 (degrees)
tick_t <- c(0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875)
tick_labels <- c("0°", "45°", "90°", "135°", "180°", "225°", "270°", "315°")
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)
}
a_col <- "bearing"
g_col <- "group"
bins <- 72 # stacking resolution (sectors)
groups <- grouped_turns(df, a_col, g_col, c("control", "magnet", "anosmic"), 6)
gap <- 0.55 / length(groups) # one ring per group, inner to outer
dots <- do.call(rbind, lapply(seq_along(groups), function(i) { b <- pmin(bins - 1, floor(groups[[i]] * bins))
data.frame(g = names(groups)[i], ring = i, x = (b + 0.5) / bins, level = stats::ave(b, b, FUN = seq_along) - 1) })) # dots stack outward
step <- min(0.024, gap * 0.9 / max(dots$level + 1, 1), 2 * pi * 0.45 / bins)
dots$r <- 0.4 + (dots$ring - 1) * gap + 0.42 * step + dots$level * step
rings <- data.frame(g = names(groups), r = 0.4 + (seq_along(groups) - 1) * gap)
means <- do.call(rbind, lapply(names(groups), function(g) { s <- circ_stats(groups[[g]]); data.frame(g = g, mu = s[["mean"]], len = 0.36 * s[["rbar"]]) }))
dots$g <- factor(dots$g, levels = names(groups)); means$g <- factor(means$g, levels = names(groups))
p <- ggplot(dots) + geom_hline(data = rings, aes(yintercept = r), colour = grey_col) +
geom_point(aes(x, r, colour = g, shape = g), size = 1.2) + # shape per group, as in the app
geom_segment(data = means, aes(x = mu, xend = mu, y = 0, yend = len, colour = g, linetype = g), linewidth = 0.8, arrow = grid::arrow(length = grid::unit(0.15, "cm"), type = "closed"), show.legend = FALSE) +
dial + scale_y_continuous(limits = c(0, 1), breaks = NULL) +
scale_colour_manual(values = if (is.null(g_col)) ref_col else cs_cat, guide = if (is.null(g_col)) "none" else "legend") +
scale_shape_manual(values = cs_shapes, guide = if (is.null(g_col)) "none" else "legend") + scale_linetype_manual(values = cs_linetypes, guide = "none") +
labs(x = NULL, y = NULL, colour = g_col, shape = g_col) + theme_cs
print(p)Needs ggplot2 · reads circular-dot-demo.csv · app theme from the optional codesplashr helper