svgbrushablearea
Area chart
How large is a quantity over time (and how do overlapping series compare)?
How to read it
- Read the top edge of each area as its value.
- Where areas overlap, follow the edges: the series aren't stacked.
- Check the baseline: a filled area implies a meaningful zero.
- Callout 1: This series' top edge is its value.
- Callout 2: Overlap: both series are measured from zero.
- Callout 3: Series cross here.
Watch out
- If zero means nothing for this measure (temperature, an index), use a line instead.
Defaults
- Resample
- ISO week
- Combine values into days, weeks or months before plotting, to reduce noise.
- Also: None (raw) · Day · Month · Quarter
- Zero baseline
- On
- Start the y axis at zero.
- Fill opacity
- 0.2
- How see-through the filled areas are.
- Range 0.1 to 0.8, step 0.05
Pinned in the code
- Same resampling as the line chart (UTC period start; ISO weeks; period mean).
- Areas are filled down to zero by default, so the area is proportional to the value; turn the baseline off only for values far from zero.
- Series overlap (they are not stacked); see the stacked-area recipe for parts of a whole.
- All calendar arithmetic is in UTC; timestamps are epoch milliseconds.
Use with care
Filled areas imply magnitude from zero — keep the zero baseline unless the values are far from zero.
# Area chart — Codesplash Chart Lab (recipe "area")
# controls: period=week, zero=true, opacity=0.2
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
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("area-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["day"] = pd.to_datetime(df["day"])
df["platform"] = pd.Categorical(df["platform"].astype("string"), categories=["Web", "App"])
def freq_levels(s, k=8):
"""Declared level order when the column is categorical, else by descending count (ties A→Z)."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(v) for v in s.cat.categories][:k]
vc = s.dropna().astype(str).value_counts()
return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def period_start(t, period):
"""UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp."""
if period == "none":
return t
day = t.dt.floor("D")
if period == "day":
return day
if period == "week":
return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
return t.dt.to_period({"month": "M", "quarter": "Q", "year": "Y"}[period]).dt.start_time
def resample(d, time, value, period, level=0.95):
"""Per period: n, mean, SD (n − 1), min, max and mean ± t(0.975, n − 1)·SD/√n (no band when n = 1)."""
d = d.dropna(subset=[time, value])
s = d.groupby(period_start(d[time], period))[value].agg(["count", "mean", "std", "min", "max"])
s = s.rename(columns={"count": "n"}).rename_axis("t").reset_index()
half = (stats.t.ppf(1 - (1 - level) / 2, s["n"] - 1) * s["std"] / np.sqrt(s["n"])).fillna(0)
return s.assign(lo=s["mean"] - half, hi=s["mean"] + half)
PERIOD = "week"
series = [(lv, df[df["platform"].astype(str) == lv]) for lv in freq_levels(df["platform"], 8)]
fig, ax = plt.subplots(figsize=(8, 4))
for i, (name, d) in enumerate(series): # overlapping areas, not stacked
s = resample(d, "day", "active_users", PERIOD)
col = PALETTE[i % len(PALETTE)]
ax.fill_between(s["t"], 0, s["mean"], color=col, alpha=0.2, linewidth=0) # filled down to zero: area ∝ value
ax.plot(s["t"], s["mean"], color=col, linewidth=1.6, label=name)
ax.set_ylabel("active_users")
ax.set_xlabel("day (UTC)")
ax.legend(title="platform", fontsize=8)
plt.show()Needs pandas, numpy, matplotlib, scipy · reads area-demo.csv · app theme from the optional codesplash helper
# Area chart — Codesplash Chart Lab (recipe "area")
# controls: period=week, zero=true, opacity=0.2
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
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("area-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["day"] = pd.to_datetime(df["day"])
df["platform"] = pd.Categorical(df["platform"].astype("string"), categories=["Web", "App"])
def freq_levels(s, k=8):
"""Declared level order when the column is categorical, else by descending count (ties A→Z)."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(v) for v in s.cat.categories][:k]
vc = s.dropna().astype(str).value_counts()
return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def period_start(t, period):
"""UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp."""
if period == "none":
return t
day = t.dt.floor("D")
if period == "day":
return day
if period == "week":
return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
return t.dt.to_period({"month": "M", "quarter": "Q", "year": "Y"}[period]).dt.start_time
def resample(d, time, value, period, level=0.95):
"""Per period: n, mean, SD (n − 1), min, max and mean ± t(0.975, n − 1)·SD/√n (no band when n = 1)."""
d = d.dropna(subset=[time, value])
s = d.groupby(period_start(d[time], period))[value].agg(["count", "mean", "std", "min", "max"])
s = s.rename(columns={"count": "n"}).rename_axis("t").reset_index()
half = (stats.t.ppf(1 - (1 - level) / 2, s["n"] - 1) * s["std"] / np.sqrt(s["n"])).fillna(0)
return s.assign(lo=s["mean"] - half, hi=s["mean"] + half)
def rgba(hex_colour, alpha):
h = hex_colour.lstrip("#")
return f"rgba({int(h[0:2], 16)}, {int(h[2:4], 16)}, {int(h[4:6], 16)}, {alpha})"
PERIOD = "week"
series = [(lv, df[df["platform"].astype(str) == lv]) for lv in freq_levels(df["platform"], 8)]
fig = go.Figure()
for i, (name, d) in enumerate(series):
s = resample(d, "day", "active_users", PERIOD)
col = PALETTE[i % len(PALETTE)]
fig.add_scatter(x=s["t"], y=s["mean"], mode="lines", name=name, line_color=col, fill="tozeroy", fillcolor=rgba(col, 0.2))
fig.update_layout(xaxis_title="day (UTC)", yaxis_title="active_users")
fig.show()Needs pandas, numpy, plotly, scipy · reads area-demo.csv · app theme from the optional codesplash helper
# Area chart — Codesplash Chart Lab (recipe "area")
# controls: period=week, zero=true, opacity=0.2
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_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
df <- read.csv("area-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["day"]] <- as.POSIXct(df[["day"]], tz = "UTC")
df[["platform"]] <- factor(df[["platform"]], levels = c("Web", "App"))
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["platform"]], "cs_declared") <- TRUE # stored level order
period_start <- function(t, period) {
# UTC period start: day, ISO week (Monday), month, quarter or year; "none" keeps the timestamp
t <- as.POSIXct(t, tz = "UTC")
if (period == "none") return(t)
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(period,
day = day,
week = day - ((lt$wday + 6) %% 7) * 86400,
month = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon + 1), tz = "UTC"),
quarter = as.POSIXct(sprintf("%d-%02d-01", lt$year + 1900, lt$mon - lt$mon %% 3 + 1), tz = "UTC"),
year = as.POSIXct(sprintf("%d-01-01", lt$year + 1900), tz = "UTC"))
}
resample_stats <- function(t, v, period, level = 0.95) {
# per period: n, mean, SD (n - 1), min, max and mean ± t(0.975, n - 1)·SD/√n (no band when n = 1)
ok <- !is.na(t) & is.finite(v)
k <- as.numeric(period_start(t[ok], period))
out <- do.call(rbind, lapply(split(v[ok], k), function(s) {
n <- length(s); sdv <- if (n > 1) stats::sd(s) else 0
half <- if (n > 1) stats::qt(1 - (1 - level) / 2, n - 1) * sdv / sqrt(n) else 0
data.frame(n = n, mean = mean(s), sd = sdv, min = min(s), max = max(s), lo = mean(s) - half, hi = mean(s) + half)
}))
out$t <- as.POSIXct(as.numeric(names(split(v[ok], k))), origin = "1970-01-01", tz = "UTC")
out[order(out$t), , drop = FALSE]
}
period <- "week"
series <- lapply(stats::setNames(nm = freq_levels(df[["platform"]], 8)), function(lv) df[as.character(df[["platform"]]) %in% lv, , drop = FALSE])
stats_df <- do.call(rbind, lapply(names(series), function(nm) cbind(series = nm, resample_stats(series[[nm]][["day"]], series[[nm]][["active_users"]], period))))
stats_df$series <- factor(stats_df$series, levels = names(series))
stats_df$base <- 0 # filled down to zero: area ∝ value
p <- ggplot(stats_df, aes(t, mean, colour = series, fill = series)) +
geom_ribbon(aes(ymin = base, ymax = mean), alpha = 0.2, colour = NA) + # overlapping, not stacked
geom_line(linewidth = 0.7) +
scale_colour_manual(values = cs_cat, name = "platform") + scale_fill_manual(values = cs_cat, guide = "none") +
scale_linetype_manual(values = cs_linetypes, name = "platform") +
labs(x = "day (UTC)", y = "active_users") +
theme_cs
print(p)Needs ggplot2 · reads area-demo.csv · app theme from the optional codesplashr helper
-- Area chart — Codesplash Chart Lab (recipe "area")
-- controls: period=week, zero=true, opacity=0.2
-- period mean per series (UTC); the area fills from zero
SELECT "platform", date_trunc('week', "day") AS t, avg("active_users") AS mean, count("active_users") AS n
FROM read_csv('area-demo.csv')
WHERE "day" IS NOT NULL AND "active_users" IS NOT NULL
GROUP BY ALL
ORDER BY ALL;Needs duckdb · reads area-demo.csv