svgbrushablebar-grouped
Grouped bars
How do category counts compare across subgroups?
How to read it
- Compare the same colour across clusters to see how one subgroup changes across categories.
- Compare colours within a cluster to see how subgroups differ inside one category.
- Use shares within subgroup when subgroup sizes differ.
- Callout 1: One cluster: one category, split by subgroup.
- 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
# Grouped bars — Codesplash Chart Lab (recipe "bar-grouped")
# controls: value=count, top=8, labels=false
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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,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
long = values.stack().rename("value").reset_index()
colors = {s: ("#9aa0a6" if s == "Other" else PALETTE[j % len(PALETTE)]) for j, s in enumerate(values.columns)}
fig = px.bar(long, x="plan", y="value", color="region", barmode="group",
category_orders={"plan": list(values.index), "region": list(values.columns)},
color_discrete_map=colors,
pattern_shape="region", pattern_shape_map={s: SERIES_HATCHES[7 if s == "Other" else j % 8] for j, s in enumerate(values.columns)}) # texture per subgroup, as in the app
fig.update_traces(marker_pattern_fgcolor=HATCH_INK, marker_pattern_fillmode="overlay")
fig.update_layout(xaxis_title="plan", yaxis_title="Count")
fig.show()Needs pandas, numpy, plotly · reads bar-grouped-demo.csv · app theme from the optional codesplash helper
# Grouped bars — Codesplash Chart Lab (recipe "bar-grouped")
# controls: value=count, top=8, labels=false
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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_textures <- function(cols, idx = seq_along(cols), bg = "#ffffff") {
# solid, hatch, dots, back-hatch, rows, cross, columns, grid: stripes and dots in the surface colour at 50 %, over the series colour
ink <- grDevices::adjustcolor(bg, alpha.f = 0.5)
seg <- function(x0, y0, x1, y1) grid::segmentsGrob(x0, y0, x1, y1, gp = grid::gpar(col = ink, lwd = 1.2))
marks <- list(NULL, seg(0, 0, 1, 1), grid::circleGrob(0.5, 0.5, r = 0.22, gp = grid::gpar(fill = ink, col = NA)), seg(0, 1, 1, 0),
seg(0, 0.5, 1, 0.5), grid::gList(seg(0, 0, 1, 1), seg(0, 1, 1, 0)), seg(0.5, 0, 0.5, 1), grid::gList(seg(0, 0.5, 1, 0.5), seg(0.5, 0, 0.5, 1)))
lapply(seq_along(cols), function(i) {
m <- marks[[(idx[[i]] - 1) %% 8 + 1]]
if (is.null(m)) return(cols[[i]])
size <- grid::unit(2.4, "mm") # the tile gets its own viewport, so npc units above are tile-relative
tile <- grid::gTree(children = grid::gList(grid::rectGrob(gp = grid::gpar(fill = cols[[i]], col = NA)), m), vp = grid::viewport(width = size, height = size))
grid::pattern(tile, width = size, height = size, extend = "repeat")
})
}
df <- read.csv("bar-grouped-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["plan"]] <- factor(df[["plan"]], levels = c("Basic", "Plus", "Pro", "Enterprise"))
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "West"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
crosstab <- function(a, b, la, lb, max_a, max_b) {
# a × b counts (rows with a missing value dropped); levels beyond the caps pool into "Other", kept last
ok <- !is.na(a) & !is.na(b)
pool <- function(v, lv, cap) {
keep <- head(lv, cap)
v <- as.character(v)
factor(ifelse(v %in% keep, v, "Other"), levels = c(keep, if (length(lv) > cap) "Other"))
}
table(category = pool(a[ok], la, max_a), group = pool(b[ok], lb, max_b))
}
tab <- crosstab(df[["plan"]], df[["region"]], levels(df[["plan"]]), levels(df[["region"]]), 8, 6)
long <- as.data.frame(tab, responseName = "n")
long$value <- long$n
fill <- setNames(rep(cs_cat, length.out = nlevels(long$group)), levels(long$group))
if ("Other" %in% names(fill)) fill[["Other"]] <- "#9aa0a6" # pooled levels in neutral grey
fill <- setNames(cs_textures(unname(fill), idx = ifelse(names(fill) == "Other", 8, seq_along(fill))), names(fill)) # texture per subgroup, as in the app
p <- ggplot(long, aes(category, value, fill = group)) +
geom_col(position = position_dodge(width = 0.85), width = 0.8) +
scale_fill_manual(values = fill, name = "region") +
labs(x = "plan", y = "Count") +
theme_cs
print(p)Needs ggplot2 · reads bar-grouped-demo.csv · app theme from the optional codesplashr helper
-- Grouped bars — Codesplash Chart Lab (recipe "bar-grouped")
-- controls: value=count, top=8, labels=false
-- category × subgroup counts; levels beyond the caps pool into 'Other'; missing rows excluded
WITH
la(level, rk) AS (VALUES ('Basic', 1), ('Plus', 2), ('Pro', 3), ('Enterprise', 4)),
lb(level, rk) AS (VALUES ('North', 1), ('South', 2), ('West', 3)),
t AS (
SELECT CASE WHEN la.rk <= 8 THEN la.level ELSE 'Other' END AS a,
CASE WHEN lb.rk <= 6 THEN lb.level ELSE 'Other' END AS b,
count(*) AS n, min(la.rk) AS ra, min(lb.rk) AS rb
FROM read_csv('bar-grouped-demo.csv') s
JOIN la ON la.level = s."plan"::VARCHAR
JOIN lb ON lb.level = s."region"::VARCHAR
GROUP BY 1, 2
)
SELECT a AS "plan", b AS "region", n,
n / sum(n) OVER (PARTITION BY b) AS share_within_region
FROM t
ORDER BY ra, rb;Needs duckdb · reads bar-grouped-demo.csv