svgtarget-progress
Progress to target
How far along is each group towards its target?
How to read it
- Read each bar as actual as a share of target.
- Compare with the 100% line.
- Colour tells you who met the target.
- Callout 1: Past the line: target met.
- Callout 2: The 100% line.
- Callout 3: Share of target, with values.
Watch out
- Targets vary by group: a big share against a small target can be less than it looks.
Defaults
- Aggregate
- Sum
- How rows combine into one number per group or period, such as a sum or a mean.
- Also: Mean · Median · Count · Minimum · Maximum
- Fixed target (0 = none)
- 0
- Used when no target column is bound
- Range 0 to 1,000,000,000,000, step 1
- Sort
- Progress (highest first)
- How rows are sorted.
- Also: Actual (largest first) · Group order
- Number format
- Compact (1.2K, 3.4M)
- How the numbers display: currency, percent, compact.
- Also: Number · Integer · Percent (of a fraction) · Currency (USD)
Pinned in the code
- Progress = actual / target per group, both aggregated the same way; groups without a target show “no target”.
- The axis runs from 0 to at least 120% so the 100% line is always visible; bars beyond the axis are capped.
- Aggregates use non-missing values: sum, mean, median (quantile type 7), count, minimum, maximum.
Use with care
Aggregates the rows the chart is given. In dashboards use a KPI widget: it computes the value over every row in the warehouse, whereas a chart draws a sample.
# Progress to target — Codesplash Chart Lab (recipe "target-progress")
# controls: agg=sum, target=0, sort=progress, format=compact
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("target-progress-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])
GRAIN_ALIAS = {"month": "M", "quarter": "Q", "year": "Y"}
STEP = {"day": pd.DateOffset(days=1), "week": pd.DateOffset(weeks=1), "month": pd.DateOffset(months=1),
"quarter": pd.DateOffset(months=3), "year": pd.DateOffset(years=1)}
CURRENCY = {"USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "CN¥", "INR": "₹", "KRW": "₩", "CAD": "CA$", "AUD": "A$"}
def period_start(t, grain):
"""UTC period start (ISO weeks start on Monday), like DuckDB date_trunc."""
day = t.dt.floor("D")
if grain == "day":
return day
if grain == "week":
return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
return t.dt.to_period(GRAIN_ALIAS[grain]).dt.start_time
def agg(s, how):
"""sum, mean, median (quantile type 7), count, min or max over the non-missing values."""
s = pd.to_numeric(s, errors="coerce").dropna()
if how == "count":
return float(len(s))
if s.empty:
return float("nan")
return float(s.quantile(0.5) if how == "median" else getattr(s, how)())
def period_series(d, time, value, grain, how):
"""One row per period (t = period start, v = the aggregate), oldest first."""
d = d.dropna(subset=[time])
v = d.groupby(period_start(d[time], grain))[value].apply(lambda s: agg(s, how))
return v.rename_axis("t").reset_index(name="v").sort_values("t", ignore_index=True)
def kpi(d, time, value, target, grain, how, points, compare):
"""The latest period against the previous one, the sparkline series and the target."""
if time is None:
return dict(value=agg(d[value], how), n=int(d[value].notna().sum()), previous=None, delta=None, pct=None,
period=None, prev_period=None, series=None, target=agg(d[target], how) if target else None)
s = period_series(d, time, value, grain, how)
latest = s.iloc[-1]
prev_t = latest["t"] - STEP[grain]
prev = s.loc[s["t"] == prev_t, "v"]
previous = float(prev.iloc[0]) if compare and len(prev) and np.isfinite(prev.iloc[0]) else None
delta = float(latest["v"]) - previous if previous is not None else None
pct = delta / abs(previous) if delta is not None and previous != 0 else None
rows = d[d[time].notna() & (period_start(d[time], grain) == latest["t"])]
return dict(value=float(latest["v"]), n=len(rows), previous=previous, delta=delta, pct=pct, period=latest["t"],
prev_period=prev_t if compare else None, series=s.tail(max(2, points)) if points else None,
target=agg(rows[target], how) if target else None)
def _group(a, d):
return f"{a:,.{d}f}"
def _trim(s):
return s.rstrip("0").rstrip(".") if "." in s else s
def _is_zero(s):
return all(ch in "0.," for ch in s if ch.isdigit() or ch in ".,")
def _kpi_body(v, style, decimals, currency):
cur = (currency or "USD").strip().upper() or "USD"
a = abs(v)
if decimals is None:
decimals = {"number": 0 if float(v).is_integer() else 2, "integer": 0, "percent": 1, "compact": 1,
"currency": 0 if cur in ("JPY", "KRW") else 2}[style]
if style == "percent":
return _group(a * 100, decimals) + "%"
if style == "currency":
return CURRENCY.get(cur, cur + " ") + _group(a, decimals)
if style == "compact":
units = [(1.0, ""), (1e3, "K"), (1e6, "M"), (1e9, "B"), (1e12, "T")]
i = max((k for k, (u, _) in enumerate(units) if a >= u), default=0)
while float(f"{a / units[i][0]:.{decimals}f}") >= 1000 and i + 1 < len(units):
i += 1 # a mantissa that rounds to 1000 moves up a unit
return _trim(_group(a / units[i][0], decimals)) + units[i][1]
return _group(a, decimals)
def fmt_kpi(v, style="compact", decimals=None, currency="USD", prefix="", suffix=""):
"""The app's KPI number format (crates/cs-dash/src/format.rs): half to even, "," thousands,
true minus (none when the value rounds to zero); number: 0 decimals when whole else 2."""
if v is None or not np.isfinite(v):
return "—"
text = _kpi_body(v, style, decimals, currency)
return ("−" if v < 0 and not _is_zero(text) else "") + prefix + text + suffix
def fmt_delta(delta, pct, style="compact", decimals=None, currency="USD"):
"""A signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs."""
if delta is None:
return ""
if not np.isfinite(delta):
return "—"
if style == "percent":
text = _group(abs(delta) * 100, 1 if decimals is None else decimals) + " pp"
else:
text = _kpi_body(abs(delta), style, decimals, currency)
out = ("" if _is_zero(text) else "−" if delta < 0 else "+") + text
if pct is not None and np.isfinite(pct):
pt = _group(abs(pct) * 100, 1)
out += " (" + ("" if _is_zero(pt) else "−" if pct < 0 else "+") + pt + "%)"
return out
def period_name(t, grain):
if t is None:
return ""
t = pd.Timestamp(t)
return {"day": t.strftime("%Y-%m-%d"), "week": "Week of " + t.strftime("%Y-%m-%d"), "month": t.strftime("%b %Y"),
"quarter": f"Q{(t.month - 1) // 3 + 1} {t.year}", "year": str(t.year)}[grain]
def tone_of(delta, good):
"""1 = good change, -1 = bad, 0 = neutral or none."""
if delta is None or delta == 0 or good == "neutral":
return 0
return 1 if (delta > 0) == (good == "up") else -1
def target_rows(d, group, value, target, how, fixed, levels):
"""Per group: the aggregate of the values and of the targets (or the fixed target)."""
out = []
for lv in levels:
g = d[d[group].astype(str) == lv]
t = agg(g[target], how) if target else fixed
out.append(dict(group=lv, value=agg(g[value], how), target=np.nan if t is None else t, n=len(g)))
out = pd.DataFrame(out)
out["variance"] = out["value"] - out["target"]
out["variance_pct"] = (out["variance"] / out["target"].abs()).replace([np.inf, -np.inf], np.nan)
out["progress"] = (out["value"] / out["target"]).replace([np.inf, -np.inf], np.nan)
return out
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]
AGG, STYLE, GOOD = "sum", "compact", "up"
FIXED_TARGET = None # used when no target column is bound
COL, PASS, FAIL, MUTED, TRACK, FG = "#2971c6", "#187c49", "#c9302d", "#626a75", "#e5e8ec", "#131922"
rows = target_rows(df, "region", "revenue", "target", AGG, FIXED_TARGET, freq_levels(df["region"], 12))
SORT = "progress"
if SORT != "order":
rows = rows.sort_values("value" if SORT == "value" else "progress", ascending=False, na_position="last")
top = max(1.2, np.ceil(np.nanmax(np.r_[rows["progress"], 0]) * 10) / 10)
fig, ax = plt.subplots(figsize=(8, 0.6 + 0.6 * len(rows)))
ys = np.arange(len(rows))[::-1]
ax.barh(ys, top, color=MUTED, alpha=0.08, height=0.7)
ax.barh(ys, np.minimum(rows["progress"].fillna(0), top), height=0.7, color=[PASS if p >= 1 else COL for p in rows["progress"].fillna(0)])
ax.axvline(1, color=MUTED, linestyle="--", linewidth=1)
for y, r in zip(ys, rows.itertuples()):
text = "no target" if not np.isfinite(r.target) else f"{fmt_kpi(r.progress, 'percent', 0)} {fmt_kpi(r.value)} / {fmt_kpi(r.target)}"
ax.text(top * 1.01, y, text, va="center", fontsize=9)
ax.set_yticks(ys, rows["group"])
ax.set_xlim(0, top)
ax.xaxis.set_major_formatter(lambda v, _: f"{v:.0%}")
ax.set_xlabel("% of target")
ax.spines[["top", "right"]].set_visible(False)
plt.show()Needs pandas, numpy, matplotlib · reads target-progress-demo.csv · app theme from the optional codesplash helper
# Progress to target — Codesplash Chart Lab (recipe "target-progress")
# controls: agg=sum, target=0, sort=progress, format=compact
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("target-progress-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["region"] = pd.Categorical(df["region"].astype("string"), categories=["North", "South", "East", "West"])
GRAIN_ALIAS = {"month": "M", "quarter": "Q", "year": "Y"}
STEP = {"day": pd.DateOffset(days=1), "week": pd.DateOffset(weeks=1), "month": pd.DateOffset(months=1),
"quarter": pd.DateOffset(months=3), "year": pd.DateOffset(years=1)}
CURRENCY = {"USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "CNY": "CN¥", "INR": "₹", "KRW": "₩", "CAD": "CA$", "AUD": "A$"}
def period_start(t, grain):
"""UTC period start (ISO weeks start on Monday), like DuckDB date_trunc."""
day = t.dt.floor("D")
if grain == "day":
return day
if grain == "week":
return day - pd.to_timedelta(day.dt.day_of_week, unit="D")
return t.dt.to_period(GRAIN_ALIAS[grain]).dt.start_time
def agg(s, how):
"""sum, mean, median (quantile type 7), count, min or max over the non-missing values."""
s = pd.to_numeric(s, errors="coerce").dropna()
if how == "count":
return float(len(s))
if s.empty:
return float("nan")
return float(s.quantile(0.5) if how == "median" else getattr(s, how)())
def period_series(d, time, value, grain, how):
"""One row per period (t = period start, v = the aggregate), oldest first."""
d = d.dropna(subset=[time])
v = d.groupby(period_start(d[time], grain))[value].apply(lambda s: agg(s, how))
return v.rename_axis("t").reset_index(name="v").sort_values("t", ignore_index=True)
def kpi(d, time, value, target, grain, how, points, compare):
"""The latest period against the previous one, the sparkline series and the target."""
if time is None:
return dict(value=agg(d[value], how), n=int(d[value].notna().sum()), previous=None, delta=None, pct=None,
period=None, prev_period=None, series=None, target=agg(d[target], how) if target else None)
s = period_series(d, time, value, grain, how)
latest = s.iloc[-1]
prev_t = latest["t"] - STEP[grain]
prev = s.loc[s["t"] == prev_t, "v"]
previous = float(prev.iloc[0]) if compare and len(prev) and np.isfinite(prev.iloc[0]) else None
delta = float(latest["v"]) - previous if previous is not None else None
pct = delta / abs(previous) if delta is not None and previous != 0 else None
rows = d[d[time].notna() & (period_start(d[time], grain) == latest["t"])]
return dict(value=float(latest["v"]), n=len(rows), previous=previous, delta=delta, pct=pct, period=latest["t"],
prev_period=prev_t if compare else None, series=s.tail(max(2, points)) if points else None,
target=agg(rows[target], how) if target else None)
def _group(a, d):
return f"{a:,.{d}f}"
def _trim(s):
return s.rstrip("0").rstrip(".") if "." in s else s
def _is_zero(s):
return all(ch in "0.," for ch in s if ch.isdigit() or ch in ".,")
def _kpi_body(v, style, decimals, currency):
cur = (currency or "USD").strip().upper() or "USD"
a = abs(v)
if decimals is None:
decimals = {"number": 0 if float(v).is_integer() else 2, "integer": 0, "percent": 1, "compact": 1,
"currency": 0 if cur in ("JPY", "KRW") else 2}[style]
if style == "percent":
return _group(a * 100, decimals) + "%"
if style == "currency":
return CURRENCY.get(cur, cur + " ") + _group(a, decimals)
if style == "compact":
units = [(1.0, ""), (1e3, "K"), (1e6, "M"), (1e9, "B"), (1e12, "T")]
i = max((k for k, (u, _) in enumerate(units) if a >= u), default=0)
while float(f"{a / units[i][0]:.{decimals}f}") >= 1000 and i + 1 < len(units):
i += 1 # a mantissa that rounds to 1000 moves up a unit
return _trim(_group(a / units[i][0], decimals)) + units[i][1]
return _group(a, decimals)
def fmt_kpi(v, style="compact", decimals=None, currency="USD", prefix="", suffix=""):
"""The app's KPI number format (crates/cs-dash/src/format.rs): half to even, "," thousands,
true minus (none when the value rounds to zero); number: 0 decimals when whole else 2."""
if v is None or not np.isfinite(v):
return "—"
text = _kpi_body(v, style, decimals, currency)
return ("−" if v < 0 and not _is_zero(text) else "") + prefix + text + suffix
def fmt_delta(delta, pct, style="compact", decimals=None, currency="USD"):
"""A signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs."""
if delta is None:
return ""
if not np.isfinite(delta):
return "—"
if style == "percent":
text = _group(abs(delta) * 100, 1 if decimals is None else decimals) + " pp"
else:
text = _kpi_body(abs(delta), style, decimals, currency)
out = ("" if _is_zero(text) else "−" if delta < 0 else "+") + text
if pct is not None and np.isfinite(pct):
pt = _group(abs(pct) * 100, 1)
out += " (" + ("" if _is_zero(pt) else "−" if pct < 0 else "+") + pt + "%)"
return out
def period_name(t, grain):
if t is None:
return ""
t = pd.Timestamp(t)
return {"day": t.strftime("%Y-%m-%d"), "week": "Week of " + t.strftime("%Y-%m-%d"), "month": t.strftime("%b %Y"),
"quarter": f"Q{(t.month - 1) // 3 + 1} {t.year}", "year": str(t.year)}[grain]
def tone_of(delta, good):
"""1 = good change, -1 = bad, 0 = neutral or none."""
if delta is None or delta == 0 or good == "neutral":
return 0
return 1 if (delta > 0) == (good == "up") else -1
def target_rows(d, group, value, target, how, fixed, levels):
"""Per group: the aggregate of the values and of the targets (or the fixed target)."""
out = []
for lv in levels:
g = d[d[group].astype(str) == lv]
t = agg(g[target], how) if target else fixed
out.append(dict(group=lv, value=agg(g[value], how), target=np.nan if t is None else t, n=len(g)))
out = pd.DataFrame(out)
out["variance"] = out["value"] - out["target"]
out["variance_pct"] = (out["variance"] / out["target"].abs()).replace([np.inf, -np.inf], np.nan)
out["progress"] = (out["value"] / out["target"]).replace([np.inf, -np.inf], np.nan)
return out
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]
AGG, STYLE, GOOD = "sum", "compact", "up"
FIXED_TARGET = None # used when no target column is bound
COL, PASS, FAIL, MUTED, TRACK, FG = "#2971c6", "#187c49", "#c9302d", "#626a75", "#e5e8ec", "#131922"
rows = target_rows(df, "region", "revenue", "target", AGG, FIXED_TARGET, freq_levels(df["region"], 12))
SORT = "progress"
if SORT != "order":
rows = rows.sort_values("value" if SORT == "value" else "progress", ascending=False, na_position="last")
top = max(1.2, np.ceil(np.nanmax(np.r_[rows["progress"], 0]) * 10) / 10)
labels = ["no target" if not np.isfinite(t) else f"{fmt_kpi(p, 'percent', 0)} {fmt_kpi(v)} / {fmt_kpi(t)}"
for p, v, t in zip(rows["progress"], rows["value"], rows["target"])]
fig = go.Figure(go.Bar(
y=rows["group"], x=np.minimum(rows["progress"].fillna(0), top), orientation="h", text=labels, textposition="outside",
marker_color=[PASS if p >= 1 else COL for p in rows["progress"].fillna(0)], cliponaxis=False))
fig.add_vline(x=1, line_dash="dash", line_color=MUTED)
fig.update_layout(width=760, height=120 + 50 * len(rows), xaxis=dict(range=[0, top], tickformat=".0%", title="% of target"),
yaxis=dict(autorange="reversed"), margin=dict(r=170), showlegend=False)
fig.show()Needs pandas, numpy, plotly · reads target-progress-demo.csv · app theme from the optional codesplash helper
# Progress to target — Codesplash Chart Lab (recipe "target-progress")
# controls: agg=sum, target=0, sort=progress, format=compact
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("target-progress-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["region"]] <- factor(df[["region"]], levels = c("North", "South", "East", "West"))
period_start <- function(t, grain) {
# UTC period start (ISO weeks start on Monday), like DuckDB date_trunc
t <- as.POSIXct(t, tz = "UTC")
lt <- as.POSIXlt(t, tz = "UTC")
day <- as.POSIXct(format(t, "%Y-%m-%d", tz = "UTC"), tz = "UTC")
switch(grain,
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"))
}
shift_months <- function(t, k) {
lt <- as.POSIXlt(t, tz = "UTC")
m <- (lt$year + 1900) * 12 + lt$mon - k
as.POSIXct(sprintf("%d-%02d-01", m %/% 12, m %% 12 + 1), tz = "UTC")
}
previous_period <- function(t, grain) {
switch(grain, day = t - 86400, week = t - 7 * 86400, month = shift_months(t, 1), quarter = shift_months(t, 3), year = shift_months(t, 12))
}
agg <- function(v, how) {
# sum, mean, median (quantile type 7), count, min or max over the non-missing values
v <- suppressWarnings(as.numeric(v))
v <- v[is.finite(v)]
if (how == "count") return(as.numeric(length(v)))
if (!length(v)) return(NA_real_)
switch(how, sum = sum(v), mean = mean(v), median = unname(stats::quantile(v, 0.5, type = 7)), min = min(v), max = max(v))
}
period_series <- function(d, time, value, grain, how) {
# one row per period (t = period start, v = the aggregate), oldest first
d <- d[!is.na(d[[time]]), , drop = FALSE]
parts <- split(d[[value]], as.numeric(period_start(d[[time]], grain)))
s <- data.frame(t = as.POSIXct(as.numeric(names(parts)), origin = "1970-01-01", tz = "UTC"), v = vapply(parts, agg, numeric(1), how = how))
s <- s[order(s$t), , drop = FALSE]
rownames(s) <- NULL
s
}
kpi <- function(d, time, value, target, grain, how, points, compare) {
# the latest period against the previous one, the sparkline series and the target
if (is.null(time)) {
return(list(value = agg(d[[value]], how), n = sum(!is.na(d[[value]])), previous = NULL, delta = NULL, pct = NULL,
period = NULL, prev_period = NULL, series = NULL, target = if (is.null(target)) NULL else agg(d[[target]], how)))
}
s <- period_series(d, time, value, grain, how)
latest <- s[nrow(s), ]
prev_t <- previous_period(latest$t, grain)
pv <- s$v[s$t == prev_t]
previous <- if (compare && length(pv) && is.finite(pv[1])) pv[1] else NULL
delta <- if (is.null(previous)) NULL else latest$v - previous
pct <- if (is.null(delta) || previous == 0) NULL else delta / abs(previous)
rows <- d[!is.na(d[[time]]) & period_start(d[[time]], grain) == latest$t, , drop = FALSE]
list(value = latest$v, n = nrow(rows), previous = previous, delta = delta, pct = pct, period = latest$t,
prev_period = if (compare) prev_t else NULL, series = if (points > 0) utils::tail(s, max(2, points)) else NULL,
target = if (is.null(target)) NULL else agg(rows[[target]], how))
}
cs_currency <- c(USD = "$", EUR = "\u20ac", GBP = "\u00a3", JPY = "\u00a5", CNY = "CN\u00a5", INR = "\u20b9", KRW = "\u20a9", CAD = "CA$", AUD = "A$")
kpi_group <- function(a, d) formatC(a, format = "f", digits = d, big.mark = ",")
kpi_trim <- function(s) if (grepl(".", s, fixed = TRUE)) sub("[.]$", "", sub("0+$", "", s)) else s
kpi_is_zero <- function(s) !grepl("[1-9]", s)
kpi_body <- function(v, style, decimals, currency) {
cur <- toupper(trimws(if (is.null(currency) || !nzchar(currency)) "USD" else currency))
a <- abs(v)
d <- if (!is.null(decimals)) decimals else switch(style, number = if (v == trunc(v)) 0 else 2, integer = 0, percent = 1, compact = 1,
currency = if (cur %in% c("JPY", "KRW")) 0 else 2)
switch(style,
percent = paste0(kpi_group(a * 100, d), "%"),
currency = paste0(if (is.na(cs_currency[cur])) paste0(cur, " ") else cs_currency[[cur]], kpi_group(a, d)),
compact = {
units <- c(1, 1e3, 1e6, 1e9, 1e12)
unit <- c("", "K", "M", "B", "T")
i <- max(c(1, which(a >= units)))
# a mantissa that rounds to 1000 moves up a unit
while (as.numeric(formatC(a / units[i], format = "f", digits = d)) >= 1000 && i < length(units)) i <- i + 1
paste0(kpi_trim(kpi_group(a / units[i], d)), unit[i])
},
kpi_group(a, d))
}
fmt_kpi <- function(v, style = "compact", decimals = NULL, currency = "USD", prefix = "", suffix = "") {
# the app's KPI number format (crates/cs-dash/src/format.rs): half to even, "," thousands,
# true minus (none when the value rounds to zero); number: 0 decimals when whole else 2
if (is.null(v) || length(v) != 1 || is.na(v) || !is.finite(v)) return("\u2014")
text <- kpi_body(v, style, decimals, currency)
paste0(if (v < 0 && !kpi_is_zero(text)) "\u2212" else "", prefix, text, suffix)
}
fmt_delta <- function(delta, pct, style = "compact", decimals = NULL, currency = "USD") {
# a signed change with the relative change ("+1,234 (+12.3%)"); percentage points for percent KPIs
if (is.null(delta)) return("")
if (is.na(delta) || !is.finite(delta)) return("\u2014")
text <- if (style == "percent") paste0(kpi_group(abs(delta) * 100, if (is.null(decimals)) 1 else decimals), " pp") else kpi_body(abs(delta), style, decimals, currency)
out <- paste0(if (kpi_is_zero(text)) "" else if (delta < 0) "\u2212" else "+", text)
if (!is.null(pct) && is.finite(pct)) {
pt <- kpi_group(abs(pct) * 100, 1)
out <- paste0(out, " (", if (kpi_is_zero(pt)) "" else if (pct < 0) "\u2212" else "+", pt, "%)")
}
out
}
period_name <- function(t, grain) {
if (is.null(t)) return("")
switch(grain,
day = format(t, "%Y-%m-%d", tz = "UTC"),
week = paste("Week of", format(t, "%Y-%m-%d", tz = "UTC")),
month = format(t, "%b %Y", tz = "UTC"),
quarter = sprintf("Q%d %s", as.POSIXlt(t, tz = "UTC")$mon %/% 3 + 1, format(t, "%Y", tz = "UTC")),
year = format(t, "%Y", tz = "UTC"))
}
tone_of <- function(delta, good) {
# 1 = good change, -1 = bad, 0 = neutral or none
if (is.null(delta) || delta == 0 || good == "neutral") return(0)
if ((delta > 0) == (good == "up")) 1 else -1
}
target_rows <- function(d, group, value, target, how, fixed, levels) {
# per group: the aggregate of the values and of the targets (or the fixed target)
out <- do.call(rbind, lapply(levels, function(lv) {
g <- d[as.character(d[[group]]) %in% lv, , drop = FALSE]
t <- if (is.null(target)) (if (is.null(fixed)) NA_real_ else fixed) else agg(g[[target]], how)
data.frame(group = lv, value = agg(g[[value]], how), target = t, n = nrow(g))
}))
out$variance <- out$value - out$target
out$variance_pct <- ifelse(is.finite(out$target) & out$target != 0, out$variance / abs(out$target), NA_real_)
out$progress <- ifelse(is.finite(out$target) & out$target != 0, out$value / out$target, NA_real_)
out
}
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[["region"]], "cs_declared") <- TRUE # stored level order
AGG <- "sum"; STYLE <- "compact"; GOOD <- "up"
FIXED_TARGET <- NULL # used when no target column is bound
col <- "#2971c6"; pass <- "#187c49"; fail <- "#c9302d"; muted <- "#626a75"; track <- "#e5e8ec"; fg <- "#131922"
rows <- target_rows(df, "region", "revenue", "target", AGG, FIXED_TARGET, freq_levels(df[["region"]], 12))
SORT <- "progress"
if (SORT != "order") rows <- rows[order(-rows[[if (SORT == "value") "value" else "progress"]], na.last = TRUE), ]
top <- max(1.2, ceiling(max(c(rows$progress, 0), na.rm = TRUE) * 10) / 10)
rows$group <- factor(rows$group, levels = rev(rows$group))
rows$shown <- pmin(ifelse(is.na(rows$progress), 0, rows$progress), top)
rows$label <- ifelse(is.na(rows$progress), "no target", paste0(vapply(rows$progress, fmt_kpi, character(1), style = "percent", decimals = 0), " ", vapply(rows$value, fmt_kpi, character(1)), " / ", vapply(rows$target, fmt_kpi, character(1))))
p <- ggplot(rows, aes(shown, group)) +
geom_col(aes(x = top), fill = muted, alpha = 0.08, width = 0.7) +
geom_col(aes(fill = I(ifelse(shown >= 1, pass, col))), width = 0.7) +
geom_vline(xintercept = 1, linetype = "dashed", colour = muted) +
geom_text(aes(x = top, label = label), hjust = -0.05, size = 3.2, colour = fg) +
scale_x_continuous(labels = function(v) paste0(round(v * 100), "%"), limits = c(0, top * 1.6), breaks = seq(0, top, 0.2), expand = c(0, 0)) +
labs(x = "% of target", y = NULL) +
theme_cs
print(p)Needs ggplot2 · reads target-progress-demo.csv · app theme from the optional codesplashr helper
-- Progress to target — Codesplash Chart Lab (recipe "target-progress")
-- controls: agg=sum, target=0, sort=progress, format=compact
-- per group: sum of the value and the target
WITH g AS (
SELECT "region" AS "group", sum("revenue") AS actual, sum("target") AS target, count(*) AS n
FROM read_csv('target-progress-demo.csv')
WHERE "region" IS NOT NULL
GROUP BY 1
)
SELECT "group", actual, target, actual / nullif(target, 0) AS progress, n
FROM g
ORDER BY n DESC, "group"Needs duckdb · reads target-progress-demo.csv