Skip to content
svgsunburst

Sunburst

How is a total split across two or three levels of categories?

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

How to read it

  1. Start at the centre: the inner ring is the top level.
  2. Move outward: each outer ring splits the slice inside it.
  3. Read arc length as share; the legend lists the top-level shares.
  1. Callout 1: The centre shows the total.
  2. Callout 2: Outer rings split the segment inside them.
  3. 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

  • plotly's sunburst lays slices out counter-clockwise; the app (and the matplotlib/ggplot2 versions) go clockwise from 12 o'clock.