svgrose-diagram
Rose diagram
Which directions or times of day are most common?
How to read it
- Read petals as how many angles fall in each sector.
- Read petal area as frequency (radius grows as the square root).
- Read the arrow as the mean direction, its length as how concentrated.
- Callout 1: A large petal: a common direction.
- Callout 2: Mean direction arrow.
- Callout 3: Zero direction.
Watch out
- Sector edges matter, so check other sector counts. Area-true and radius-true petals look different.
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)
- Sectors
- 16
- How many sectors divide the circle.
- Range 4 to 72, step 1
- Area-true petals (√ radius)
- On
- Radius ∝ √count so a petal's area, not its length, is proportional to the count.
- Mean direction arrow
- On
- Arrow toward the mean direction with length R̄ (1 = all angles identical).
Pinned in the code
- Sector i covers [i·360/k, (i + 1)·360/k) in the chosen unit, starting at angle 0 (north, midnight, Monday, January).
- Petal radius ∝ √count by default (area-true, Fisher 1993 §2.2); a linear radius exaggerates large counts.
- Groups stack outward within each petal; the petal's outer edge is the sector total.
- Arrow: mean direction θ̄ = atan2(Σ sin θ, Σ cos θ), length R̄ (the dial radius is R̄ = 1).
Use with care
Sector boundaries change the picture with few angles; compare with the circular dot plot.
# Rose diagram — Codesplash Chart Lab (recipe "rose-diagram")
# controls: units=degrees, orientation=compass, bins=16, area=true, mean=true
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba
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_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5) # stripes let the chart surface show through
df = pd.read_csv("rose-diagram-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, AREA, MEAN = 16, True, True # area-true petals: radius ∝ √count
groups = grouped_turns(df, A, G, 8)
counts = np.array([np.bincount(np.minimum(BINS - 1, np.floor(t * BINS).astype(int)), minlength=BINS) for _, t in groups], dtype=float) # sector i = [i/BINS, (i+1)/BINS)
top = counts.sum(axis=0).max() or 1
radius = (lambda n: np.sqrt(n / top)) if AREA else (lambda n: n / top)
fig, ax = plt.subplots(figsize=(6.4, 6.4), subplot_kw={"projection": "polar"})
dial(ax)
acc = np.zeros(BINS)
for i, (name, _) in enumerate(groups): # groups stack outward within a petal
r0, r1 = radius(acc), radius(acc + counts[i])
ax.bar(2 * np.pi * np.arange(BINS) / BINS, r1 - r0, bottom=r0, width=2 * np.pi / BINS, align="edge", color=PALETTE[i % len(PALETTE)],
edgecolor="white", linewidth=0.5, hatch=SERIES_HATCHES[i % 8] if G else "", hatchcolor=HATCH_INK, label=name or None) # texture per group, as in the app
acc += counts[i]
if MEAN: # arrow toward the mean direction, length R̄
for i, (name, t) in enumerate(groups):
mu, rbar = circ_stats(t)
ax.annotate("", xy=(2 * np.pi * mu, rbar), xytext=(0, 0), arrowprops=dict(arrowstyle="-|>", color=PALETTE[i % len(PALETTE)] if G else REF, lw=1.8, linestyle=SERIES_DASHES[i % 8] if G else "-")) # dash per group
fr = [0.25, 0.5, 0.75, 1]
ax.set_ylim(0, 1)
ax.set_yticks(fr, [str(round(top * f * f)) if AREA else str(round(top * f)) for f in fr], fontsize=8) # ring labels are counts
if G:
ax.legend(fontsize=8, loc="upper right", bbox_to_anchor=(1.18, 1.1))
plt.show()Needs pandas, numpy, matplotlib · reads rose-diagram-demo.csv · app theme from the optional codesplash helper
# Rose diagram — Codesplash Chart Lab (recipe "rose-diagram")
# controls: units=degrees, orientation=compass, bins=16, area=true, mean=true
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_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,0.5)" # stripes let the chart surface show through
df = pd.read_csv("rose-diagram-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, AREA, MEAN = 16, True, True
groups = grouped_turns(df, A, G, 8)
counts = np.array([np.bincount(np.minimum(BINS - 1, np.floor(t * BINS).astype(int)), minlength=BINS) for _, t in groups], dtype=float)
top = counts.sum(axis=0).max() or 1
radius = (lambda n: np.sqrt(n / top)) if AREA else (lambda n: n / top)
theta = 360 * (np.arange(BINS) + 0.5) / BINS
fig = go.Figure()
acc = np.zeros(BINS)
for i, (name, _) in enumerate(groups):
r0, r1 = radius(acc), radius(acc + counts[i])
fig.add_barpolar(r=r1 - r0, base=r0, theta=theta, width=360 / BINS, name=name or A, marker=dict(color=PALETTE[i % len(PALETTE)], line=dict(color="white", width=0.5),
pattern=dict(shape=SERIES_HATCHES[i % 8] if G else "", fgcolor=HATCH_INK, fillmode="overlay")), # texture per group, as in the app
customdata=counts[i], hovertemplate="%{theta:.0f}: %{customdata}<extra></extra>")
acc += counts[i]
if MEAN:
for i, (name, t) in enumerate(groups):
mu, rbar = circ_stats(t)
fig.add_scatterpolar(r=[0, rbar], theta=[360 * mu] * 2, mode="lines+markers", marker=dict(size=[0, 9], symbol="triangle-up", color=PALETTE[i % len(PALETTE)] if G else REF),
line=dict(color=PALETTE[i % len(PALETTE)] if G else REF, width=2, dash=SERIES_DASHES[i % 8] if G else "solid"), name=f"mean {name}".strip(), showlegend=False)
fr = [0.25, 0.5, 0.75, 1]
fig.update_layout(polar=dict(**POLAR, radialaxis=dict(range=[0, 1], tickvals=fr, ticktext=[str(round(top * f * f)) if AREA else str(round(top * f)) for f in fr])), barmode="overlay", showlegend=bool(G))
fig.show()Needs pandas, numpy, plotly · reads rose-diagram-demo.csv · app theme from the optional codesplash helper
# Rose diagram — Codesplash Chart Lab (recipe "rose-diagram")
# controls: units=degrees, orientation=compass, bins=16, area=true, mean=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))
# 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_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("rose-diagram-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 <- 16; area <- TRUE; show_mean <- TRUE # area-true petals: radius ∝ √count
groups <- grouped_turns(df, a_col, g_col, c("control", "magnet", "anosmic"), 8)
counts <- t(vapply(groups, function(t) as.numeric(tabulate(pmin(bins, floor(t * bins) + 1), nbins = bins)), numeric(bins))) # sector i = [i/bins, (i+1)/bins)
top <- max(colSums(counts), 1)
radius <- if (area) function(n) sqrt(n / top) else function(n) n / top
acc <- numeric(bins)
petals <- do.call(rbind, lapply(seq_along(groups), function(i) { r0 <- radius(acc); acc <<- acc + counts[i, ]
data.frame(g = names(groups)[i], x0 = (seq_len(bins) - 1) / bins, x1 = seq_len(bins) / bins, r0 = r0, r1 = radius(acc)) })) # groups stack outward
petals$g <- factor(petals$g, levels = names(groups))
means <- do.call(rbind, lapply(names(groups), function(g) { s <- circ_stats(groups[[g]]); data.frame(g = g, mu = s[["mean"]], rbar = s[["rbar"]]) }))
means$g <- factor(means$g, levels = names(groups))
fr <- c(0.25, 0.5, 0.75, 1)
p <- ggplot(petals) + geom_rect(aes(xmin = x0, xmax = x1, ymin = r0, ymax = r1, fill = g), colour = "white", linewidth = 0.25) +
{ if (show_mean) geom_segment(data = means, aes(x = mu, xend = mu, y = 0, yend = rbar, colour = g, linetype = g), linewidth = 0.9, arrow = grid::arrow(length = grid::unit(0.18, "cm"), type = "closed")) } +
dial + scale_y_continuous(limits = c(0, 1), breaks = fr, labels = if (area) round(top * fr^2) else round(top * fr)) +
scale_fill_manual(values = cs_textures(cs_cat), guide = if (is.null(g_col)) "none" else "legend") + # texture per group, as in the app
scale_colour_manual(values = if (is.null(g_col)) ref_col else cs_cat, guide = "none") + scale_linetype_manual(values = cs_linetypes, guide = "none") +
labs(x = NULL, y = NULL, fill = g_col) + theme_cs
print(p)Needs ggplot2 · reads rose-diagram-demo.csv · app theme from the optional codesplashr helper