Skip to content
svgbrushablebar-grouped

Grouped bars

How do category counts compare across subgroups?

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

How to read it

  1. Compare the same colour across clusters to see how one subgroup changes across categories.
  2. Compare colours within a cluster to see how subgroups differ inside one category.
  3. Use shares within subgroup when subgroup sizes differ.
  1. Callout 1: One cluster: one category, split by subgroup.
  2. Callout 2: Same colour, next cluster: how that subgroup changes.

Watch out

  • More than about four subgroups becomes hard to compare. Try small multiples.

Defaults

Value
Count
Show counts or shares.
Also: % within subgroup
Top categories
8
How many categories to show; the rest are grouped.
Range 3 to 20, step 1
Value labels
Off
Print each value on the chart.

Pinned in the code

  • Category levels follow the data dictionary order, else descending frequency; levels beyond the top k (6 for subgroups) pool into “Other”, drawn in neutral grey.
  • “% within subgroup” divides each count by its subgroup total, so every colour sums to 100 % across categories (column percentages of the category × subgroup table).
  • Rows with a missing category or subgroup are excluded.
# Grouped bars — Codesplash Chart Lab (recipe "bar-grouped")
# controls: value=count, top=8, labels=false
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba

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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "////", "..", "\\\\\\\\", "---", "xx", "|||", "++"]
HATCH_INK = to_rgba(plt.rcParams["axes.facecolor"], 0.5)  # stripes let the chart surface show through

df = pd.read_csv("bar-grouped-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["plan"] = pd.Categorical(df["plan"].astype("string"), categories=["Basic", "Plus", "Pro", "Enterprise"])
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "West"])

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, "plan", "region", 8, 6)  # categories × subgroups
values = tab
colors = ["#9aa0a6" if s == "Other" else PALETTE[j % len(PALETTE)] for j, s in enumerate(values.columns)]

fig, ax = plt.subplots(figsize=(8, 4.5))
xs = np.arange(len(values.index))
k = len(values.columns)
width = 0.8 / k
for j, s in enumerate(values.columns):
    hatch = SERIES_HATCHES[7 if s == "Other" else j % 8]  # texture per subgroup, as in the app
    bars = ax.bar(xs + (j - (k - 1) / 2) * width, values[s].fillna(0), width, label=s, color=colors[j], hatch=hatch, hatchcolor=HATCH_INK, linewidth=0)
ax.set_xticks(xs, list(values.index))
ax.set_xlabel("plan")
ax.set_ylabel("Count")
ax.legend(title="region")
plt.show()

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