svgbrushablearea-stacked
Stacked area
How does the mix of a total change over time?
How to read it
- Read the top edge for the total.
- Read the band thickness for each series; the bottom band shares a flat baseline.
- Switch to 100% to see the mix change without the total's growth.
- Callout 1: Top edge: the total.
- Callout 2: Bottom band: the easiest series to read, because its baseline is flat.
- Callout 3: Upper bands ride on the ones below; read their thickness.
Watch out
- Upper bands look like they grow whenever the bands below grow. Compare thickness, not height.
Defaults
- 100 % stacked
- Off
- Show each series as a share of the total, so you compare the mix rather than the size.
- Series shown
- 6
- How many series to show; the rest are grouped.
- Range 2 to 8, step 1
Pinned in the code
- Value per (time, series) = sum of the value column (row count when none); times are the distinct x values.
- Series ordered by total, largest at the bottom; beyond the limit they are pooled as “Other” (grey).
- 100 %: each series divided by the time point's total.
- Only the bottom series has a common baseline: compare upper layers with care, or use small multiples.
# Stacked area — Codesplash Chart Lab (recipe "area-stacked")
# controls: percent=false, series=6
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("area-stacked-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])
OTHER = "#9aa0a6" # pooled levels
d = df[df["month"].notna()].copy()
d["_s"] = d["product_line"].astype(object).where(d["product_line"].notna(), "(missing)").astype(str)
d["_v"] = d["revenue_k"].where(np.isfinite(d["revenue_k"]), 0).fillna(0) # value summed per time and series
totals = d.groupby("_s")["_v"].sum()
if isinstance(df["product_line"].dtype, pd.CategoricalDtype): # declared order, else largest total first
declared = [str(l) for l in df["product_line"].cat.categories]
ranked = [l for l in declared if l in totals.index] + [s for s in totals.index if s not in declared]
else:
ranked = sorted(totals.index, key=lambda s: (-totals[s], s))
keep = ranked[: 6 - 1] if len(ranked) > 6 else ranked # beyond the limit → "Other"
series = keep + (["Other"] if len(ranked) > len(keep) else [])
d["_s"] = d["_s"].where(d["_s"].isin(keep), "Other")
wide = d.pivot_table(index="month", columns="_s", values="_v", aggfunc="sum", fill_value=0).reindex(columns=series, fill_value=0).sort_index()
colors = [OTHER if s == "Other" else PALETTE[i % len(PALETTE)] for i, s in enumerate(series)]
hatches = [SERIES_HATCHES[7 if s == "Other" else i % 8] for i, s in enumerate(series)] # texture per layer, as in the app
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.stackplot(wide.index, wide.T.to_numpy(), labels=series, colors=colors, alpha=0.9, hatch=hatches, hatchcolor=HATCH_INK, linewidth=0) # first series at the bottom
ax.set_xlabel("month")
ax.set_ylabel("revenue_k")
ax.legend(title="product_line", loc="upper left", bbox_to_anchor=(1.01, 1))
plt.show()Needs pandas, numpy, matplotlib · reads area-stacked-demo.csv · app theme from the optional codesplash helper
# Stacked area — Codesplash Chart Lab (recipe "area-stacked")
# controls: percent=false, series=6
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("area-stacked-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["month"] = pd.to_datetime(df["month"])
OTHER = "#9aa0a6" # pooled levels
d = df[df["month"].notna()].copy()
d["_s"] = d["product_line"].astype(object).where(d["product_line"].notna(), "(missing)").astype(str)
d["_v"] = d["revenue_k"].where(np.isfinite(d["revenue_k"]), 0).fillna(0) # value summed per time and series
totals = d.groupby("_s")["_v"].sum()
if isinstance(df["product_line"].dtype, pd.CategoricalDtype): # declared order, else largest total first
declared = [str(l) for l in df["product_line"].cat.categories]
ranked = [l for l in declared if l in totals.index] + [s for s in totals.index if s not in declared]
else:
ranked = sorted(totals.index, key=lambda s: (-totals[s], s))
keep = ranked[: 6 - 1] if len(ranked) > 6 else ranked # beyond the limit → "Other"
series = keep + (["Other"] if len(ranked) > len(keep) else [])
d["_s"] = d["_s"].where(d["_s"].isin(keep), "Other")
wide = d.pivot_table(index="month", columns="_s", values="_v", aggfunc="sum", fill_value=0).reindex(columns=series, fill_value=0).sort_index()
colors = [OTHER if s == "Other" else PALETTE[i % len(PALETTE)] for i, s in enumerate(series)]
hatches = [SERIES_HATCHES[7 if s == "Other" else i % 8] for i, s in enumerate(series)] # texture per layer, as in the app
fig = go.Figure()
for s, color, h in zip(series, colors, hatches):
fig.add_scatter(x=wide.index, y=wide[s], name=s, mode="lines", stackgroup="one", line=dict(width=0.5, color=color), fillcolor=color, fillpattern=dict(shape=h, fgcolor=HATCH_INK, fillmode="overlay"))
fig.update_layout(xaxis_title="month", yaxis_title="revenue_k", legend_title_text="product_line")
fig.show()Needs pandas, numpy, plotly · reads area-stacked-demo.csv · app theme from the optional codesplash helper
# Stacked area — Codesplash Chart Lab (recipe "area-stacked")
# controls: percent=false, series=6
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("area-stacked-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["month"]] <- as.POSIXct(df[["month"]], tz = "UTC")
df[["product_line"]] <- factor(df[["product_line"]])
update_geom_defaults("text", list(colour = "#131922")) # labels in the theme's text colour
ok <- !is.na(df[["month"]])
times <- sort(unique(df[["month"]][ok]))
ti <- match(df[["month"]][ok], times)
s <- as.character(df[["product_line"]][ok])
s[is.na(s)] <- "(missing)"
v <- df[["revenue_k"]][ok]
v[!is.finite(v)] <- 0
totals <- tapply(v, s, sum)
ranked <- names(totals)[order(-totals, names(totals))] # largest total first
keep <- if (length(ranked) > 6) head(ranked, 6 - 1) else ranked # beyond the limit → "Other"
series <- c(keep, if (length(ranked) > length(keep)) "Other")
s <- ifelse(s %in% keep, s, "Other")
m <- tapply(v, list(ti, factor(s, levels = series)), sum)
m[is.na(m)] <- 0
top <- m
for (j in seq_len(ncol(m))[-1]) top[, j] <- top[, j - 1] + m[, j] # first series at the bottom
long <- data.frame(time = rep(times, ncol(m)), series = factor(rep(series, each = length(times)), levels = series),
ymin = as.vector(top - m), ymax = as.vector(top))
fill <- setNames(rep(cs_cat, length.out = length(series)), series)
fill[series == "Other"] <- "#9aa0a6"
fill <- setNames(cs_textures(unname(fill), idx = ifelse(series == "Other", 8, seq_along(series))), series) # texture per layer, as in the app
p <- ggplot(long, aes(time, ymin = ymin, ymax = ymax, fill = series)) +
geom_ribbon(alpha = 0.9) +
scale_fill_manual(values = fill, name = "product_line") +
labs(x = "month", y = "revenue_k") +
theme_cs
print(p)Needs ggplot2 · reads area-stacked-demo.csv · app theme from the optional codesplashr helper
-- Stacked area — Codesplash Chart Lab (recipe "area-stacked")
-- controls: percent=false, series=6
-- value per (time, series); series ranked by total (largest first), beyond 6 pooled into 'Other'
WITH d AS (
SELECT "month" AS t, coalesce("product_line"::VARCHAR, '(missing)') AS s,
CASE WHEN isfinite("revenue_k") THEN "revenue_k" ELSE 0 END AS v
FROM read_csv('area-stacked-demo.csv') WHERE "month" IS NOT NULL
),
r AS (SELECT s, row_number() OVER (ORDER BY sum(v) DESC, s) AS rk, count(*) OVER () AS k FROM d GROUP BY s),
p AS (
SELECT d.t, CASE WHEN r.k <= 6 OR r.rk < 6 THEN d.s ELSE 'Other' END AS series, r.rk, d.v
FROM d JOIN r USING (s)
)
SELECT t, series, sum(v) AS value, sum(v) / sum(sum(v)) OVER (PARTITION BY t) AS share
FROM p
GROUP BY t, series
ORDER BY t, min(rk);Needs duckdb · reads area-stacked-demo.csv