svgsunburst
Sunburst
How is a total split across two or three levels of categories?
How to read it
- Start at the centre: the inner ring is the top level.
- Move outward: each outer ring splits the slice inside it.
- Read arc length as share; the legend lists the top-level shares.
- Callout 1: The centre shows the total.
- Callout 2: Outer rings split the segment inside them.
- Callout 3: Legend: top-level shares.
Watch out
- Outer arcs look bigger than inner arcs of the same share. Use an icicle for accurate comparison.
Defaults
- Children per node
- 8
- How many sub-levels to show under each parent; the rest are grouped.
- Range 3 to 20, step 1
Pinned in the code
- Angle ∝ sum of the size column (row count when none); rings are equal width, one per level; the centre shows the total.
- Children sorted by value; beyond the limit pooled as “Other”.
- Colour follows the top-level ancestor, lighter for deeper rings; labels only on arcs wide enough to hold them.
- Angles are harder to compare than lengths — prefer an icicle or treemap for precise comparison.
Use with care
Outer-ring angles are hard to compare; use the icicle for precise reading.
# Sunburst — Codesplash Chart Lab (recipe "sunburst")
# controls: maxChildren=8
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"]
df = pd.read_csv("sunburst-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=["Web", "App", "Store"])
def tree_nodes(frame, levels, size=None, max_children=10):
"""Hierarchy nodes like the app: value = sum of size (rows counted when none, non-positive rows skipped);
children sorted by value (ties alphabetical); beyond max_children the smallest pool into "Other";
missing labels become "(missing)". Returns depth-first rows: id, label, parent, value, depth, top."""
w = pd.to_numeric(frame[size], errors="coerce") if size else pd.Series(1.0, index=frame.index)
w = w.where(np.isfinite(w), 0).fillna(0)
keep = w > 0
sub = frame.loc[keep, levels].astype(object)
paths = sub.where(sub.notna(), "(missing)").astype(str)
w = w[keep]
nodes = []
def walk(index, depth, parent, top):
if depth == len(levels):
return
key = paths.loc[index, levels[depth]]
sums = w.loc[index].groupby(key).sum()
kids = sorted(sums.items(), key=lambda kv: (-kv[1], kv[0]))
shown = kids[: max_children - 1] if len(kids) > max_children else kids
entries = [(name, value, False) for name, value in shown]
if len(kids) > len(shown):
entries.append(("Other", sum(v for _, v in kids[len(shown):]), True))
entries.sort(key=lambda e: (-e[1], e[2])) # d3 re-sorts siblings by value; "Other" last among ties
for name, value, pooled in entries:
nid = f"{parent} › {name}"
nodes.append({"id": nid, "label": name, "parent": parent, "value": value, "depth": depth + 1, "top": top or name})
if not pooled:
walk(index[(key == name).to_numpy()], depth + 1, nid, top or name)
walk(paths.index, 0, "All", None)
return pd.DataFrame(nodes)
def partition(nodes):
"""Each node's span [x0, x1) as a share of the total; children split the parent's span by value."""
span = {"All": (0.0, 1.0)}
pvalue = {"All": nodes.loc[nodes["depth"] == 1, "value"].sum()}
cursor = {"All": 0.0}
x0s, x1s = [], []
for nd in nodes.itertuples(): # depth-first: parents come before their children
p0, p1 = span[nd.parent]
width = (p1 - p0) * nd.value / pvalue[nd.parent]
x0 = p0 + cursor[nd.parent]
cursor[nd.parent] += width
span[nd.id], pvalue[nd.id], cursor[nd.id] = (x0, x0 + width), nd.value, 0.0
x0s.append(x0)
x1s.append(x0 + width)
return nodes.assign(x0=x0s, x1=x1s)
OTHER = "#9aa0a6" # pooled levels
nodes = tree_nodes(df, ["category", "subcategory", "channel"], "revenue", max_children=8)
nodes = partition(nodes)
tops = list(nodes.loc[nodes["depth"] == 1, "label"])
top_color = {t: (OTHER if t == "Other" else PALETTE[i % len(PALETTE)]) for i, t in enumerate(tops)}
ALPHA = {1: 1.0, 2: 0.72, 3: 0.5, 4: 0.36}
D = 3 # rings: equal width, the hole is one ring wide
from matplotlib.patches import Wedge
fig, ax = plt.subplots(figsize=(6.5, 6.5))
for nd in nodes.itertuples():
r_out = (nd.depth + 1) / (D + 1)
# clockwise from 12 o'clock: matplotlib angles run counter-clockwise from 3 o'clock
ax.add_patch(Wedge((0, 0), r_out, 90 - 360 * nd.x1, 90 - 360 * nd.x0, width=1 / (D + 1),
facecolor=top_color[nd.top], alpha=ALPHA.get(nd.depth, 0.36), edgecolor=plt.rcParams["axes.facecolor"], linewidth=0.8))
span = (nd.x1 - nd.x0) * 2 * np.pi * (r_out - 0.5 / (D + 1))
if span > 0.18: # labels only on arcs wide enough
a = np.pi / 2 - np.pi * (nd.x0 + nd.x1)
r = r_out - 0.5 / (D + 1)
ax.text(r * np.cos(a), r * np.sin(a), nd.label, ha="center", va="center", fontsize=6.5)
total = nodes.loc[nodes["depth"] == 1, "value"].sum()
ax.text(0, 0, f"{total:,.0f}", ha="center", va="center", fontsize=11, fontweight="bold") # the centre shows the total
ax.set_xlim(-1.02, 1.02)
ax.set_ylim(-1.02, 1.02)
ax.set_aspect("equal")
ax.axis("off")
plt.show()Needs pandas, numpy, matplotlib · reads sunburst-demo.csv · app theme from the optional codesplash helper
# Sunburst — Codesplash Chart Lab (recipe "sunburst")
# controls: maxChildren=8
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("sunburst-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=["Web", "App", "Store"])
def tree_nodes(frame, levels, size=None, max_children=10):
"""Hierarchy nodes like the app: value = sum of size (rows counted when none, non-positive rows skipped);
children sorted by value (ties alphabetical); beyond max_children the smallest pool into "Other";
missing labels become "(missing)". Returns depth-first rows: id, label, parent, value, depth, top."""
w = pd.to_numeric(frame[size], errors="coerce") if size else pd.Series(1.0, index=frame.index)
w = w.where(np.isfinite(w), 0).fillna(0)
keep = w > 0
sub = frame.loc[keep, levels].astype(object)
paths = sub.where(sub.notna(), "(missing)").astype(str)
w = w[keep]
nodes = []
def walk(index, depth, parent, top):
if depth == len(levels):
return
key = paths.loc[index, levels[depth]]
sums = w.loc[index].groupby(key).sum()
kids = sorted(sums.items(), key=lambda kv: (-kv[1], kv[0]))
shown = kids[: max_children - 1] if len(kids) > max_children else kids
entries = [(name, value, False) for name, value in shown]
if len(kids) > len(shown):
entries.append(("Other", sum(v for _, v in kids[len(shown):]), True))
entries.sort(key=lambda e: (-e[1], e[2])) # d3 re-sorts siblings by value; "Other" last among ties
for name, value, pooled in entries:
nid = f"{parent} › {name}"
nodes.append({"id": nid, "label": name, "parent": parent, "value": value, "depth": depth + 1, "top": top or name})
if not pooled:
walk(index[(key == name).to_numpy()], depth + 1, nid, top or name)
walk(paths.index, 0, "All", None)
return pd.DataFrame(nodes)
nodes = tree_nodes(df, ["category", "subcategory", "channel"], "revenue", max_children=8)
OTHER = "#9aa0a6" # pooled levels
tops = list(nodes.loc[nodes["depth"] == 1, "label"])
top_color = {t: (OTHER if t == "Other" else PALETTE[i % len(PALETTE)]) for i, t in enumerate(tops)}
ALPHA = {1: 1.0, 2: 0.72, 3: 0.5, 4: 0.36}
fig = go.Figure(go.Sunburst(
ids=nodes["id"], labels=nodes["label"], parents=["" if p == "All" else p for p in nodes["parent"]],
values=nodes["value"], branchvalues="total", sort=True,
marker=dict(colors=[top_color[t] for t in nodes["top"]]),
rotation=90, # first slice at 12 o'clock
hovertemplate="%{id}<br>%{value:,.4g} (%{percentRoot:.1%} of total)<extra></extra>",
))
fig.update_layout(margin=dict(t=30, l=10, r=10, b=10))
fig.show()Needs pandas, numpy, plotly · reads sunburst-demo.csv · app theme from the optional codesplash helper
# Sunburst — Codesplash Chart Lab (recipe "sunburst")
# controls: maxChildren=8
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("sunburst-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["category"]] <- factor(df[["category"]])
df[["subcategory"]] <- factor(df[["subcategory"]])
df[["channel"]] <- factor(df[["channel"]], levels = c("Web", "App", "Store"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
tree_nodes <- function(frame, levels, size = NULL, max_children = 10) {
# hierarchy nodes like the app: value = sum of size (rows counted when none, non-positive rows skipped);
# children sorted by value (ties alphabetical); beyond max_children the smallest pool into "Other";
# missing labels become "(missing)". Returns depth-first rows: id, label, parent, value, depth, top.
w <- if (is.null(size)) rep(1, nrow(frame)) else suppressWarnings(as.numeric(frame[[size]]))
w[!is.finite(w)] <- 0
keep <- w > 0
paths <- lapply(levels, function(l) {
v <- as.character(frame[[l]])[keep]
ifelse(is.na(v), "(missing)", v)
})
w <- w[keep]
out <- list()
walk <- function(idx, depth, parent, top) {
if (depth > length(levels)) return(invisible(NULL))
key <- paths[[depth]][idx]
sums <- tapply(w[idx], key, sum)
o <- order(-sums, names(sums))
kids <- names(sums)[o]
vals <- as.numeric(sums)[o]
m <- if (length(kids) > max_children) max_children - 1 else length(kids)
e <- data.frame(label = kids[seq_len(m)], value = vals[seq_len(m)], pooled = FALSE)
if (length(kids) > m) e <- rbind(e, data.frame(label = "Other", value = sum(vals[-seq_len(m)]), pooled = TRUE))
e <- e[order(-e$value, e$pooled), ] # d3 re-sorts siblings by value; "Other" last among ties
for (k in seq_len(nrow(e))) {
id <- paste(parent, e$label[k], sep = " \u203a ")
tp <- if (is.null(top)) e$label[k] else top
out[[length(out) + 1]] <<- data.frame(id = id, label = e$label[k], parent = parent, value = e$value[k], depth = depth, top = tp)
if (!e$pooled[k]) walk(idx[key == e$label[k]], depth + 1, id, tp)
}
}
walk(seq_along(w), 1, "All", NULL)
do.call(rbind, out)
}
partition <- function(nodes) {
# each node's span [x0, x1) as a share of the total; children split the parent's span by value
span <- list(All = c(0, 1))
pv <- c(All = sum(nodes$value[nodes$depth == 1]))
cursor <- c(All = 0)
nodes$x0 <- nodes$x1 <- NA_real_
for (i in seq_len(nrow(nodes))) { # depth-first: parents come before their children
p <- nodes$parent[i]
s <- span[[p]]
w <- (s[2] - s[1]) * nodes$value[i] / pv[[p]]
nodes$x0[i] <- s[1] + cursor[[p]]
nodes$x1[i] <- nodes$x0[i] + w
cursor[[p]] <- cursor[[p]] + w
span[[nodes$id[i]]] <- c(nodes$x0[i], nodes$x1[i])
pv[[nodes$id[i]]] <- nodes$value[i]
cursor[[nodes$id[i]]] <- 0
}
nodes
}
nodes <- tree_nodes(df, c("category", "subcategory", "channel"), "revenue", max_children = 8)
nodes <- partition(nodes)
tops <- nodes$label[nodes$depth == 1]
top_color <- setNames(rep(cs_cat, length.out = length(tops)), tops)
top_color[tops == "Other"] <- "#9aa0a6"
nodes$fill <- top_color[nodes$top]
nodes$alpha <- c(1, 0.72, 0.5, 0.36)[pmin(nodes$depth, 4)] # lighter for deeper levels
D <- 3 # rings: equal width, the hole is one ring wide
nodes$mid <- (nodes$x0 + nodes$x1) / 2
nodes$show <- (nodes$x1 - nodes$x0) * 2 * pi * (nodes$depth + 0.5) / (D + 1) > 0.18 # labels only on wide arcs
total <- sum(nodes$value[nodes$depth == 1])
p <- ggplot(nodes) +
geom_rect(aes(xmin = depth, xmax = depth + 1, ymin = x0, ymax = x1, fill = fill, alpha = alpha), colour = "white", linewidth = 0.3) +
geom_text(data = nodes[nodes$show, ], aes(x = depth + 0.5, y = mid, label = label), size = 2.2) +
annotate("text", x = 0, y = 0, label = format(round(total), big.mark = ","), fontface = "bold", size = 4) + # the centre shows the total
scale_fill_identity() +
scale_alpha_identity() +
scale_x_continuous(limits = c(0, D + 1)) +
scale_y_continuous(limits = c(0, 1), expand = c(0, 0)) +
coord_polar(theta = "y", start = 0, direction = 1) + # clockwise from 12 o'clock
theme_cs +
theme(axis.text = element_blank(), axis.title = element_blank(), axis.ticks = element_blank(), axis.line = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank())
print(p)Needs ggplot2 · reads sunburst-demo.csv · app theme from the optional codesplashr helper
-- Sunburst — Codesplash Chart Lab (recipe "sunburst")
-- controls: maxChildren=8
-- node totals for every prefix of the hierarchy (ROLLUP) and each node's rank among its siblings;
-- the app pools siblings with rank ≥ 8 into "Other" when a parent has more than 8 children
WITH d AS (SELECT coalesce("category"::VARCHAR, '(missing)') AS "category", coalesce("subcategory"::VARCHAR, '(missing)') AS "subcategory", coalesce("channel"::VARCHAR, '(missing)') AS "channel", CASE WHEN isfinite("revenue") THEN "revenue" ELSE 0 END AS w FROM read_csv('sunburst-demo.csv')),
nodes AS (
SELECT "category", "subcategory", "channel", (1 - grouping("category")) + (1 - grouping("subcategory")) + (1 - grouping("channel")) AS depth, sum(w) AS value
FROM d
WHERE w > 0
GROUP BY ROLLUP ("category", "subcategory", "channel")
)
SELECT *, row_number() OVER (
PARTITION BY depth, CASE WHEN depth > 1 THEN "category" END, CASE WHEN depth > 2 THEN "subcategory" END
ORDER BY value DESC, "category", "subcategory", "channel"
) AS sibling_rank -- rank among siblings (same parent path), ties alphabetical
FROM nodes
ORDER BY depth, "category", "subcategory", "channel";Needs duckdb · reads sunburst-demo.csv
- plotly's sunburst lays slices out counter-clockwise; the app (and the matplotlib/ggplot2 versions) go clockwise from 12 o'clock.