svgradial-heatmap
Radial heatmap
How does activity vary round the clock (or the year), for each day, store or segment?
How to read it
- Read rings as categories and sectors as times.
- Find the dark sectors: when each category peaks.
- Compare between rings for different rhythms.
- Callout 1: A dark sector: a busy time.
- Callout 2: Ring labels: categories.
- Callout 3: Time starts at the top.
Watch out
- Outer rings look larger for the same sector. Compare colour, not area.
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)
- Sectors
- 24
- How many sectors divide the circle.
- Range 4 to 96, step 1
- Cell value
- Count of rows
- What each cell's colour shows, such as a count, a sum or a mean.
- Also: Sum of value · Mean of value
Pinned in the code
- Sector i covers [i/k, (i + 1)/k) of the cycle from angle 0; rings run inner to outer in level order.
- Sequential colour from the lowest to the highest cell (count, sum or mean); empty cells are drawn dim.
Use with care
Outer rings are larger than inner ones; read colour, not area.
# Radial heatmap — Codesplash Chart Lab (recipe "radial-heatmap")
# controls: units=hours, orientation=compass, bins=24, stat=count
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
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("radial-heatmap-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["weekday"] = pd.Categorical(df["weekday"].astype("string"), categories=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
_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)
A = "hour"
RING = "weekday"
V = "spend"
BINS, STAT = 24, "count" # cell value: count, sum or mean
d = df.dropna(subset=[A] + ([V] if V else []))
rings = freq_levels(d[RING], 12) if RING else ["all"] # inner to outer
ri = d[RING].astype(str).map({r: i for i, r in enumerate(rings)}) if RING else pd.Series(0, index=d.index)
d, ri = d[ri.notna()], ri[ri.notna()].astype(int).to_numpy()
b = np.minimum(BINS - 1, np.floor(to_turn(d[A]) * BINS).astype(int))
x = d[V].to_numpy(float) if V else np.ones(len(d))
total, count = np.zeros((len(rings), BINS)), np.zeros((len(rings), BINS))
np.add.at(total, (ri, b), x)
np.add.at(count, (ri, b), 1)
with np.errstate(invalid="ignore", divide="ignore"):
cell = count if STAT == "count" else total if STAT == "sum" else np.where(count > 0, total / count, np.nan)
finite = cell[np.isfinite(cell)]
lo, hi = min(finite.min(), 0), max(finite.max(), 1)
cmap = LinearSegmentedColormap.from_list("seq", SEQ)
INNER = 0.22
w = (1 - INNER) / len(rings)
fig, ax = plt.subplots(figsize=(6.8, 6.4), subplot_kw={"projection": "polar"})
dial(ax)
start = 2 * np.pi * np.arange(BINS) / BINS
for i in range(len(rings)):
colours = [cmap((v - lo) / (hi - lo)) if np.isfinite(v) else GREY for v in cell[i]]
ax.bar(start, w * 0.97, bottom=INNER + i * w, width=2 * np.pi / BINS, align="edge", color=colours, edgecolor="white", linewidth=0.3)
ax.set_ylim(0, 1)
ax.set_yticks([INNER + (i + 0.5) * w for i in range(len(rings))], rings if RING else [""], fontsize=7)
fig.colorbar(plt.cm.ScalarMappable(norm=plt.Normalize(lo, hi), cmap=cmap), ax=ax, shrink=0.7, pad=0.1, label=STAT if STAT == "count" or not V else f"{STAT} of {V}")
plt.show()Needs pandas, numpy, matplotlib · reads radial-heatmap-demo.csv · app theme from the optional codesplash helper
# Radial heatmap — Codesplash Chart Lab (recipe "radial-heatmap")
# controls: units=hours, orientation=compass, bins=24, stat=count
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
df = pd.read_csv("radial-heatmap-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["weekday"] = pd.Categorical(df["weekday"].astype("string"), categories=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
_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))
A = "hour"
RING = "weekday"
V = "spend"
BINS, STAT = 24, "count"
d = df.dropna(subset=[A] + ([V] if V else []))
rings = freq_levels(d[RING], 12) if RING else ["all"]
ri = d[RING].astype(str).map({r: i for i, r in enumerate(rings)}) if RING else pd.Series(0, index=d.index)
d, ri = d[ri.notna()], ri[ri.notna()].astype(int).to_numpy()
b = np.minimum(BINS - 1, np.floor(to_turn(d[A]) * BINS).astype(int))
x = d[V].to_numpy(float) if V else np.ones(len(d))
total, count = np.zeros((len(rings), BINS)), np.zeros((len(rings), BINS))
np.add.at(total, (ri, b), x)
np.add.at(count, (ri, b), 1)
with np.errstate(invalid="ignore", divide="ignore"):
cell = count if STAT == "count" else total if STAT == "sum" else np.where(count > 0, total / count, np.nan)
finite = cell[np.isfinite(cell)]
lo, hi = float(min(finite.min(), 0)), float(max(finite.max(), 1))
INNER = 0.22
w = (1 - INNER) / len(rings)
scale = [[i / (len(SEQ) - 1), col] for i, col in enumerate(SEQ)]
fig = go.Figure()
for i, ring in enumerate(rings):
fig.add_barpolar(r=[w * 0.97] * BINS, base=INNER + i * w, theta=360 * (np.arange(BINS) + 0.5) / BINS, width=360 / BINS, name=str(ring),
marker=dict(color=cell[i], colorscale=scale, cmin=lo, cmax=hi, showscale=i == 0, line=dict(color="white", width=0.3)),
customdata=cell[i], hovertemplate=str(ring) + " %{theta:.0f}: %{customdata:.3g}<extra></extra>")
fig.update_layout(polar=dict(**POLAR, radialaxis=dict(range=[0, 1], tickvals=[INNER + (i + 0.5) * w for i in range(len(rings))], ticktext=rings)), showlegend=False)
fig.show()Needs pandas, numpy, plotly · reads radial-heatmap-demo.csv · app theme from the optional codesplash helper
# Radial heatmap — Codesplash Chart Lab (recipe "radial-heatmap")
# controls: units=hours, orientation=compass, bins=24, stat=count
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("radial-heatmap-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["weekday"]] <- factor(df[["weekday"]], levels = c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"))
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)))
a_col <- "hour"
ring_col <- "weekday"
v_col <- "spend"
bins <- 24; stat <- "count" # cell value: count, sum or mean
d <- df[!is.na(df[[a_col]]) & (if (is.null(v_col)) TRUE else !is.na(df[[v_col]])), ]
rings <- if (is.null(ring_col)) "all" else levels_of(d[[ring_col]], c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"), 12) # inner to outer
ri <- if (is.null(ring_col)) rep(1L, nrow(d)) else match(as.character(d[[ring_col]]), rings)
keep <- !is.na(ri); d <- d[keep, ]; ri <- ri[keep]
b <- pmin(bins - 1, floor(to_turn(d[[a_col]]) * bins))
x <- if (is.null(v_col)) rep(1, nrow(d)) else d[[v_col]]
total <- tapply(x, list(factor(ri, levels = seq_along(rings)), factor(b, levels = 0:(bins - 1))), sum); total[is.na(total)] <- 0
count <- table(factor(ri, levels = seq_along(rings)), factor(b, levels = 0:(bins - 1)))
cell <- if (stat == "count") unclass(count) else if (stat == "sum") total else ifelse(count > 0, total / count, NA)
lo <- min(cell, 0, na.rm = TRUE); hi <- max(cell, 1, na.rm = TRUE)
inner <- 0.22; w <- (1 - inner) / length(rings)
cells <- expand.grid(ring = seq_along(rings), bin = 0:(bins - 1))
cells$v <- cell[cbind(cells$ring, cells$bin + 1)]
p <- ggplot(cells) + geom_rect(aes(xmin = bin / bins, xmax = (bin + 1) / bins, ymin = inner + (ring - 1) * w, ymax = inner + ring * w - 0.006, fill = v), colour = "white", linewidth = 0.15) +
dial + scale_y_continuous(limits = c(0, 1), breaks = inner + (seq_along(rings) - 0.5) * w, labels = if (is.null(ring_col)) NULL else rings) +
scale_fill_gradient(low = seq_ramp[1], high = seq_ramp[length(seq_ramp)], limits = c(lo, hi), na.value = grey_col) +
labs(x = NULL, y = NULL, fill = if (stat == "count" || is.null(v_col)) stat else paste(stat, "of", v_col)) + theme_cs
print(p)Needs ggplot2 · reads radial-heatmap-demo.csv · app theme from the optional codesplashr helper