svgicicle
Icicle
How is a total split across levels, read precisely along one axis?
How to read it
- Read columns left to right: each column is one level deeper.
- Read a rectangle's height as its share.
- Follow one colour rightward to see how that group breaks down.
- Callout 1: Leftmost column: the top level.
- Callout 2: Next column: the split inside it.
- Callout 3: Thin rows: small leaves, labelled only when they fit.
Watch out
- Small rectangles lose their labels; hover or filter to read them.
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
- Height ∝ sum of the size column (row count when none); columns are the levels, outer first.
- Children sorted by value; beyond the limit pooled as “Other”.
- Same partition as the sunburst, drawn on a linear axis so values can be compared by length.
# Icicle — Codesplash Chart Lab (recipe "icicle")
# 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("icicle-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}
LEVELS = ["category", "subcategory", "channel"]
D = len(LEVELS)
from matplotlib.patches import Rectangle
fig, ax = plt.subplots(figsize=(9, 5.4))
for nd in nodes.itertuples():
x0, h = (nd.depth - 1) / D, nd.x1 - nd.x0 # one column per level, height ∝ value
ax.add_patch(Rectangle((x0, nd.x0), 1 / D, h, facecolor=top_color[nd.top], alpha=ALPHA.get(nd.depth, 0.36),
edgecolor=plt.rcParams["axes.facecolor"], linewidth=1))
if h > 0.035:
ax.text(x0 + 0.01, nd.x0 + h / 2, f"{nd.label} {nd.value:,.0f}", va="center", fontsize=7)
for d, name in enumerate(LEVELS):
ax.text((d + 0.02) / D, -0.015, name, va="bottom", fontsize=8, color="0.45") # level names as column headers
ax.set_xlim(0, 1)
ax.set_ylim(1, -0.06) # outer level first, largest at the top
ax.axis("off")
plt.show()Needs pandas, numpy, matplotlib · reads icicle-demo.csv · app theme from the optional codesplash helper
# Icicle — Codesplash Chart Lab (recipe "icicle")
# 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("icicle-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.Icicle(
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"]]),
tiling=dict(orientation="h"), # levels left to right
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 icicle-demo.csv · app theme from the optional codesplash helper
# Icicle — Codesplash Chart Lab (recipe "icicle")
# 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("icicle-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
LEVELS <- c("category", "subcategory", "channel")
p <- ggplot(nodes) +
geom_rect(aes(xmin = depth - 1, xmax = depth, ymin = 1 - x1, ymax = 1 - x0, fill = fill, alpha = alpha), colour = "white", linewidth = 0.4) +
geom_text(data = nodes[nodes$x1 - nodes$x0 > 0.035, ], aes(x = depth - 0.97, y = 1 - (x0 + x1) / 2, label = paste(label, format(round(value), big.mark = ","))), hjust = 0, size = 2.3) +
scale_fill_identity() +
scale_alpha_identity() +
scale_x_continuous(breaks = seq_along(LEVELS) - 0.5, labels = LEVELS, position = "top", expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
labs(x = NULL, y = NULL) +
theme_cs +
theme(axis.text.y = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.line = element_blank(), axis.ticks = element_blank())
print(p)Needs ggplot2 · reads icicle-demo.csv · app theme from the optional codesplashr helper
-- Icicle — Codesplash Chart Lab (recipe "icicle")
-- 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('icicle-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 icicle-demo.csv