Skip to content
svggauge

Gauge

How close is a measure to its target on a fixed scale?

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

How to read it

  1. Read the arc's length as the value on a fixed scale.
  2. Compare with the target tick.
  3. Read the coloured outer rim for the bands, if on.
  1. Callout 1: The value.
  2. Callout 2: The target tick.
  3. Callout 3: The scale's maximum.

Watch out

  • A gauge uses much space for one number and hides any trend. Pair it with a sparkline.

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
Scale maximum (0 = auto)
0
Auto: a round number ≥ 125% of the target and ≥ the value
Range 0 to 1,000,000,000,000, step 1
Target bands
On
Colour the dial by distance from the target.
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

  • The arc's angle is proportional to value / scale maximum (0 at the left end, the maximum at the right).
  • Bands outside the arc mark < 60%, 60–80% and 80–100% of target; the arc turns the pass colour when the target is met.
  • Aggregates use non-missing values: sum, mean, median (quantile type 7), count, minimum, maximum.

Use with care

Gauges use a lot of space for one number; a bullet chart or a KPI tile with a target bar shows the same information more compactly and comparably.

# Gauge — Codesplash Chart Lab (recipe "gauge")
# controls: agg=sum, target=0, max=0, bands=true, format=compact
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Wedge

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("gauge-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV

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, SCALE_MAX, SHOW_BANDS = "sum", "compact", None, True
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.assign(_all="revenue"), "_all", "revenue", "target", AGG, FIXED_TARGET, ["revenue"])

def nice_ceil(v):
    """A round scale maximum: 1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8 or 10 × a power of ten."""
    if not v > 0:
        return 1.0
    p = 10 ** np.floor(np.log10(v))
    return next(m * p for m in [1, 1.2, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10] if m * p >= v)

rows["max"] = [SCALE_MAX or nice_ceil(max(v, (0 if np.isnan(t) else t) * 1.25, 0)) for v, t in zip(rows["value"], rows["target"])]

fig, axes = plt.subplots(1, len(rows), figsize=(4 * len(rows), 3), squeeze=False)
for ax, r in zip(axes[0], rows.itertuples()):
    frac = min(max(r.value / r.max, 0), 1) if np.isfinite(r.value) else 0
    met = np.isfinite(r.target) and r.value >= r.target
    ax.add_patch(Wedge((0, 0), 1, 0, 180, width=0.2, color=TRACK))  # angles: 180° = 0, 0° = scale max
    ax.add_patch(Wedge((0, 0), 1, 180 - 180 * frac, 180, width=0.2, color=PASS if met else COL))
    if np.isfinite(r.target):
        a = np.pi * (1 - min(max(r.target / r.max, 0), 1))
        ax.plot([0.76 * np.cos(a), 1.04 * np.cos(a)], [0.76 * np.sin(a), 1.04 * np.sin(a)], color=FG, linewidth=2.5)
        if SHOW_BANDS:  # zones run bad → good along the arc, split by small gaps so they read without colour (as in the app)
            for k, (lo, hi, colour) in enumerate([(0, 0.6, FAIL), (0.6, 0.8, MUTED), (0.8, 1.0, PASS)]):
                a0 = 180 - 180 * min(hi * r.target / r.max, 1) + (0.8 if k < 2 else 0)
                a1 = 180 - 180 * min(lo * r.target / r.max, 1) - (0.8 if k > 0 else 0)
                if a1 > a0:
                    ax.add_patch(Wedge((0, 0), 1.07, a0, a1, width=0.025, color=colour, alpha=0.7))
    ax.text(0, 0.08, fmt_kpi(r.value, STYLE), ha="center", fontsize=20, fontweight="bold", color=FG)
    sub = f"{fmt_kpi(r.progress, 'percent', 0)} of {fmt_kpi(r.target, STYLE)}" if np.isfinite(r.target) else r.group
    ax.text(0, -0.12, sub, ha="center", fontsize=9, color=MUTED)
    ax.text(-0.9, -0.1, "0", ha="center", fontsize=8, color=MUTED)
    ax.text(0.9, -0.1, fmt_kpi(r.max, "compact", 0), ha="center", fontsize=8, color=MUTED)
    ax.set_title(r.group if len(rows) > 1 else "", fontsize=11)
    ax.set_xlim(-1.15, 1.15)
    ax.set_ylim(-0.25, 1.15)
    ax.set_aspect("equal")
    ax.axis("off")
plt.show()

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