svgbrushablebar-stacked
Stacked bars
How is each category made up of subgroups?
How to read it
- Read the whole bar for the total, or switch to 100% to compare composition.
- Compare the first and last segments: they share a baseline.
- Use the segment labels for the middle ones, which start at different points.
- Callout 1: Segment length: this subgroup's share.
- Callout 2: Middle segments float, so compare them by their labels.
- 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
# 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 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
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)
values = tab.div(tab.sum(axis=1).replace(0, np.nan), axis=0).fillna(0) * 100 # row %
fig = go.Figure()
for j, s in enumerate(values.columns):
v = values[s]
share = v / values.sum(axis=1).replace(0, np.nan)
text = [f"{x:.0f}%" if sh >= 0.06 else "" for x, sh in zip(v, share)] if True else None
color = "#9aa0a6" if s == "Other" else PALETTE[j % len(PALETTE)]
fig.add_bar(y=list(values.index), x=v, orientation="h", name=s, marker_color=color, text=text, textposition="inside")
fig.update_layout(barmode="stack", legend_title_text="priority",
xaxis_title="% of category", yaxis_title="team", yaxis_autorange="reversed")
fig.show()Needs pandas, numpy, plotly · reads bar-stacked-demo.csv · app theme from the optional codesplash helper
# Stacked bars — Codesplash Chart Lab (recipe "bar-stacked")
# controls: mode=percent, orientation=horizontal, top=10, labels=true
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))
df <- read.csv("bar-stacked-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["team"]] <- factor(df[["team"]])
df[["priority"]] <- factor(df[["priority"]], levels = c("Critical", "High", "Medium", "Low"))
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
freq_levels <- function(v) {
# the app's order when the data dictionary declares none: by descending frequency, ties alphabetical
t <- table(as.character(v[!is.na(v)]))
names(t)[order(-as.numeric(t), names(t))]
}
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[["team"]], df[["priority"]], freq_levels(df[["team"]]), levels(df[["priority"]]), 10, 6)
long <- as.data.frame(tab, responseName = "n")
long$value <- ave(long$n, long$category, FUN = function(v) if (sum(v) > 0) v / sum(v) * 100 else 0) # row %
long$share <- ave(long$n, long$category, FUN = function(v) if (sum(v) > 0) v / sum(v) else 0)
long$category <- factor(long$category, levels = rev(levels(long$category))) # first category on top
fill <- setNames(rep(cs_cat, length.out = nlevels(long$group)), levels(long$group))
if ("Other" %in% names(fill)) fill[["Other"]] <- "#9aa0a6"
p <- ggplot(long, aes(x = value, y = category, fill = group)) +
geom_col(position = position_stack(reverse = TRUE), width = 0.7) + # first level at the baseline
geom_text(aes(label = ifelse(share >= 0.06, sprintf("%.0f%%", value), "")),
position = position_stack(vjust = 0.5, reverse = TRUE), colour = "white", size = 2.5) +
scale_fill_manual(values = fill, name = "priority") +
labs(x = "% of category", y = "team") +
theme_cs
print(p)Needs ggplot2 · reads bar-stacked-demo.csv · app theme from the optional codesplashr helper
-- Stacked bars — Codesplash Chart Lab (recipe "bar-stacked")
-- controls: mode=percent, orientation=horizontal, top=10, labels=true
-- category × stack-level counts with row shares; levels beyond the caps pool into 'Other'
WITH
la AS (
SELECT "team"::VARCHAR AS level, row_number() OVER (ORDER BY count(*) DESC, "team"::VARCHAR) AS rk
FROM read_csv('bar-stacked-demo.csv') WHERE "team" IS NOT NULL GROUP BY 1
),
lb(level, rk) AS (VALUES ('Critical', 1), ('High', 2), ('Medium', 3), ('Low', 4)),
t AS (
SELECT CASE WHEN la.rk <= 10 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-stacked-demo.csv') s
JOIN la ON la.level = s."team"::VARCHAR
JOIN lb ON lb.level = s."priority"::VARCHAR
GROUP BY 1, 2
)
SELECT a AS "team", b AS "priority", n,
n / sum(n) OVER (PARTITION BY a) AS row_share
FROM t
ORDER BY ra, rb;Needs duckdb · reads bar-stacked-demo.csv