Skip to content
svgbrushablebar-stacked

Stacked bars

How is each category made up of subgroups?

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

How to read it

  1. Read the whole bar for the total, or switch to 100% to compare composition.
  2. Compare the first and last segments: they share a baseline.
  3. Use the segment labels for the middle ones, which start at different points.
  1. Callout 1: Segment length: this subgroup's share.
  2. Callout 2: Middle segments float, so compare them by their labels.
  3. Callout 3: The last segment lines up on the right edge when stacked to 100%.

Watch out

  • A 100% stack hides how different the totals are, so check the counts as well.

Defaults

Scale
100 %
How the values map to the axis or the colour.
Also: Count
Orientation
Bars
Draw bars vertically or horizontally; horizontal suits long labels.
Also: Columns
Top categories
10
How many categories to show; the rest are grouped.
Range 3 to 20, step 1
Segment labels
On
Print a value on each segment.

Pinned in the code

  • Segments stack in subgroup level order (dictionary order, else frequency); levels beyond the top 6 pool into “Other”.
  • 100 % mode divides by the category's row total (row percentages); segment labels show that share and are hidden when the segment is too small to hold them.
  • Only the first segment shares a common baseline — compare inner segments with the 100 % view or grouped bars.
# Stacked bars — Codesplash Chart Lab (recipe "bar-stacked")
# controls: mode=percent, orientation=horizontal, top=10, labels=true
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("bar-stacked-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["priority"] = pd.Categorical(df["priority"].astype("string"), categories=["Critical", "High", "Medium", "Low"])

def levels(s):
    """Level order like the app: declared order (categorical dtype), else by descending frequency, ties alphabetical."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [str(c) for c in s.cat.categories]
    counts = s.dropna().astype(str).value_counts()
    return sorted(counts.index, key=lambda k: (-counts[k], k))

def crosstab(frame, a, b, max_a, max_b):
    """a × b counts (rows with a missing value dropped); levels beyond the caps pool into "Other", kept last."""
    d = frame[[a, b]].dropna()
    pooled, cats = {}, []
    for col, cap in ((a, max_a), (b, max_b)):
        lv = levels(frame[col])
        keep = lv[:cap]
        v = d[col].astype(str)
        pooled[col] = v.where(v.isin(keep), "Other")
        cats.append(keep + (["Other"] if len(lv) > cap else []))
    tab = pd.crosstab(pd.Categorical(pooled[a], categories=cats[0]), pd.Categorical(pooled[b], categories=cats[1]), dropna=False)
    tab.index, tab.columns = pd.Index(cats[0], name=a), pd.Index(cats[1], name=b)
    return tab

tab = crosstab(df, "team", "priority", 10, 6)  # categories × stack levels
values = tab.div(tab.sum(axis=1).replace(0, np.nan), axis=0).fillna(0) * 100  # row %
colors = ["#9aa0a6" if s == "Other" else PALETTE[j % len(PALETTE)] for j, s in enumerate(values.columns)]
cats = list(values.index)[::-1]  # first category on top
rows = values.loc[cats]

fig, ax = plt.subplots(figsize=(8, 4.5))
base = np.zeros(len(cats))
for j, s in enumerate(values.columns):
    w = rows[s].to_numpy()
    bars = ax.barh(cats, w, left=base, color=colors[j], label=s, height=0.7)
    for rect, v, tot in zip(bars, w, rows.sum(axis=1)):  # label segments big enough to hold it
        if tot and v / tot >= 0.06:
            cx, cy = rect.get_x() + rect.get_width() / 2, rect.get_y() + rect.get_height() / 2
            ax.text(cx, cy, f"{v:.0f}%", ha="center", va="center", fontsize=7, color="white")
    base += w
ax.set_xlabel("% of category")
ax.set_ylabel("team")
ax.legend(title="priority", loc="upper left", bbox_to_anchor=(1.01, 1))
plt.show()

Needs pandas, numpy, matplotlib · reads bar-stacked-demo.csv · app theme from the optional codesplash helper