Skip to content
svgkpi-tile

KPI tile

What is the headline number now, and is it moving the right way?

Demo data · seed 20261101 · 2,924 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read the big number: the latest period's value.
  2. Read the change below it, against the previous period.
  3. Read the sparkline for context and the bar for progress to target.
  1. Callout 1: The latest value.
  2. Callout 2: Change against the previous period.
  3. Callout 3: Recent shape.
  4. Callout 4: Progress to target.

Watch out

  • An unfinished latest period makes a comparison misleading; check the period before reacting.

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
Period
Month
The length of each period: day, week, month, quarter or year.
Also: Day · ISO week · Quarter · Year
Compare with the previous period
On
Show the change against the previous period under the value.
Sparkline periods
12
How many of the latest periods the sparkline shows.
Range 0 to 60, step 1
Good direction
Higher is better
Whether up or down counts as good, which sets the colours.
Also: Lower is better · Neutral
Number format
Compact (1.2K, 3.4M)
How the numbers display: currency, percent, compact.
Also: Number · Integer · Percent (of a fraction) · Currency (USD)
Fixed target (0 = none)
0
Used when no target column is bound
Range 0 to 1,000,000,000,000, step 1

Pinned in the code

  • With a time column the value is the aggregate over the latest period (the period containing the latest timestamp); the change is against the period before it, and % change = change / |previous| (none when the previous value is 0).
  • The sparkline shows the latest N periods; empty periods are skipped, not drawn as zero.
  • Progress = value / target, where the target is the target column aggregated the same way over the same rows (or the fixed target).
  • Aggregates use non-missing values: sum, mean, median (quantile type 7), count, minimum, maximum.
  • Periods are UTC calendar periods (ISO weeks start on Monday), like DuckDB date_trunc; the latest period may be partial.
  • Numbers round half to even (compact: 1 decimal on k/M/B/T); the change is coloured by the good direction.

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.

# KPI tile — Codesplash Chart Lab (recipe "kpi-tile")
# controls: agg=sum, grain=month, compare=true, points=12, good=up, format=compact, target=0
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("kpi-tile-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["date"] = pd.to_datetime(df["date"])

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

AGG, GRAIN, POINTS, COMPARE, GOOD, STYLE = "sum", "month", 12, True, "up", "compact"
FIXED_TARGET = None  # used when no target column is bound
COL, PASS, FAIL, MUTED, TRACK, FG = "#2971c6", "#187c49", "#c9302d", "#626a75", "#e5e8ec", "#131922"
k = kpi(df, "date", "revenue", "target", GRAIN, AGG, POINTS, COMPARE)
target = k["target"] if k["target"] is not None and np.isfinite(k["target"]) else FIXED_TARGET
progress = k["value"] / target if target else None
label = "revenue · sum"
if k["period"] is None:
    caption = f"all rows (n = {k['n']:,})"
elif k["previous"] is not None:
    caption = f"{period_name(k['period'], GRAIN)} vs {period_name(k['prev_period'], GRAIN)}"
else:
    caption = period_name(k["period"], GRAIN)
delta_colour = {1: PASS, -1: FAIL, 0: MUTED}[tone_of(k["delta"], GOOD)]
target_text = f"{fmt_kpi(progress, 'percent', 0)} of target {fmt_kpi(target, STYLE)}" if target else None

fig = plt.figure(figsize=(6.4, 3.6))
fig.text(0.04, 0.88, label, fontsize=12, color=MUTED)
fig.text(0.04, 0.70, fmt_kpi(k["value"], STYLE), fontsize=40, fontweight="bold", color=FG)
fig.text(0.04, 0.61, fmt_delta(k['delta'], k['pct'], STYLE), fontsize=11, fontweight="bold", color=delta_colour)
fig.text(0.96, 0.61, caption, fontsize=11, color=MUTED, ha="right")
s = k["series"]
if s is not None and len(s) >= 2:  # sparkline: equal spacing per period, scaled to its own range
    ax = fig.add_axes([0.04, 0.2 if target else 0.06, 0.92, 0.33])
    xs = np.arange(len(s))
    ax.fill_between(xs, s["v"], s["v"].min(), color=COL, alpha=0.15, linewidth=0)
    ax.plot(xs, s["v"], color=COL, linewidth=2)
    ax.plot(xs[-1], s["v"].iloc[-1], "o", color=COL)
    ax.axis("off")
if target:  # progress to target
    fig.text(0.04, 0.095, target_text, fontsize=10, color=MUTED)
    bar = fig.add_axes([0.04, 0.05, 0.92, 0.025])
    bar.barh(0, 1, color=TRACK, height=1)
    bar.barh(0, min(max(progress, 0), 1), color=PASS if progress >= 1 else COL, height=1)
    bar.set_xlim(0, 1)
    bar.axis("off")
plt.show()

Needs pandas, numpy, matplotlib · reads kpi-tile-demo.csv · app theme from the optional codesplash helper