Skip to content
svgicicle

Icicle

How is a total split across levels, read precisely along one axis?

Demo data · seed 20261101 · 1,500 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read columns left to right: each column is one level deeper.
  2. Read a rectangle's height as its share.
  3. Follow one colour rightward to see how that group breaks down.
  1. Callout 1: Leftmost column: the top level.
  2. Callout 2: Next column: the split inside it.
  3. 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