Skip to content
ChartslibraryUI Get Pro

Target bar chart

Progress against a target per item: bar, target tick and attainment in words.

FreeMIT · install in one command<TargetBarChart />

When to use

  • Sales against quota by team
  • Spend against budget by department
  • OKR progress

When not to use

Good practice

  • Use favorable="down" when staying under the target is the goal.

Installation

Target bar chart is free under the MIT license.

$ npx shadcn@latest add https://chartslibraryui.com/r/target-bar-chart.json

Installs the chart, its dependencies and the shared core into your components folder.

Then import the theme once: import "@/components/charts/core/charts.css" Installation guide

Usage

import { TargetBarChart } from "@/components/charts/target-bar-chart";
import { regions } from "./sample-data";

export function Example() {
  return (
    <TargetBarChart
      title="Two regions are ahead of target"
      subtitle="Revenue against annual target, USD"
      data={regions}
      x="region"
      actual="revenue"
      target="target"
      format="currency"
    />
  );
}

Data

Rows with a label key, an actual key and a target key.

[{ region: "EMEA", revenue: 2.9e6, target: 2.8e6 }, ...]

Missing values are null. Invalid values make the chart say what’s wrong instead of drawing a misleading picture. How charts handle bad data

Props

Every chart also accepts the shared frame props: title, subtitle, source, height, mode, toolbar. Common API

export interface TargetBarChartProps extends FrameProps {
  data: Row[];
  /** Key of the item label. */
  x: string;
  /** Key of the actual value. */
  actual: string;
  /** Key of the target value. */
  target: string;
  format?: FormatInput;
  /** "up" when reaching or beating the target is good (sales), "down" when staying under it is (spend). */
  favorable?: Favorable;
  actualLabel?: string;
  targetLabel?: string;
}

Source

Installs target-bar-chart.tsx and the shared core/ (11 files).

View target-bar-chart.tsx
"use client";

import { useMemo, type PointerEvent } from "react";
import { AXIS_FONT } from "./core/axis";
import { color as tokens, toneOf, toneText, type Favorable } from "./core/color";
import { readNum, type Issue, type Row } from "./core/data";
import { formatValue, type FormatInput } from "./core/format";
import { ChartFrame, ChartTooltip, localPoint, useActiveIndex, type FrameProps, type LegendItem } from "./core/frame";
import { barPath } from "./core/path";
import { bandScale, linearScale } from "./core/scale";
import { textWidth, truncate } from "./core/text";

export interface TargetBarChartProps extends FrameProps {
  data: Row[];
  /** Key of the item label. */
  x: string;
  /** Key of the actual value. */
  actual: string;
  /** Key of the target value. */
  target: string;
  format?: FormatInput;
  /** "up" when reaching or beating the target is good (sales), "down" when staying under it is (spend). */
  favorable?: Favorable;
  actualLabel?: string;
  targetLabel?: string;
}

/**
 * Progress against a target per item: a bar for the actual, a tick for the target and the attainment in words.
 * Each row is scaled to the same axis, so items of different sizes stay comparable.
 */
export function TargetBarChart({
  data,
  x,
  actual,
  target,
  format,
  favorable = "up",
  actualLabel = "Actual",
  targetLabel = "Target",
  height: hProp,
  ...frame
}: TargetBarChartProps) {
  const { rows, issues } = useMemo(() => {
    const issues: Issue[] = [];
    if (!Array.isArray(data) || !data.length) return { rows: [] as { name: string; a: number | null; t: number | null }[], issues: [{ level: "error", message: "No data to display." }] as Issue[] };
    const rows = data.map((r) => {
      const a = readNum(r?.[actual]);
      const t = readNum(r?.[target]);
      if (a.state === "invalid" || t.state === "invalid") issues.push({ level: "error", message: `"${r?.[x]}" has a non-numeric value.` });
      return { name: String(r?.[x] ?? ""), a: a.value, t: t.value };
    });
    if (rows.some((r) => (r.a ?? 0) < 0 || (r.t ?? 0) < 0))
      issues.push({ level: "error", message: "Target charts need values of zero or more. For signed variance use a diverging bar chart." });
    const noTarget = rows.filter((r) => r.t === null).length;
    if (noTarget) issues.push({ level: "note", message: `${noTarget} item(s) have no target; attainment is not shown for them.` });
    return { rows, issues };
  }, [data, x, actual, target]);
  const height = hProp ?? Math.max(120, rows.length * 44 + 10);
  const legend: LegendItem[] = [
    { key: "a", label: actualLabel, color: tokens.series(0) },
    { key: "t", label: targetLabel, color: "var(--clui-ink)", shape: "line" },
  ];
  const att = (r: { a: number | null; t: number | null }) => (r.a !== null && r.t ? r.a / r.t : null);
  const table = {
    columns: [
      { key: "name", label: x },
      { key: "a", label: actualLabel, align: "right" as const, format: (v: unknown) => formatValue(v as number, format, { context: "table" }) },
      { key: "t", label: targetLabel, align: "right" as const, format: (v: unknown) => formatValue(v as number, format, { context: "table" }) },
      { key: "p", label: "Attainment", align: "right" as const, format: (v: unknown) => formatValue(v as number, { kind: "percent", decimals: 0 }) },
    ],
    rows: rows.map((r) => ({ ...r, p: att(r) })),
  };
  const summary = `${rows.length} items against target. ${rows
    .map((r) => `${r.name} ${formatValue(att(r), { kind: "percent", decimals: 0 })} of target`)
    .join("; ")}.`;
  return (
    <ChartFrame {...frame} height={height} issues={issues} table={table} summary={summary} legend={legend}>
      {({ width }) => <TargetInner {...{ width, height, rows, format, favorable, actualLabel, targetLabel, att }} />}
    </ChartFrame>
  );
}

function TargetInner(p: {
  width: number;
  height: number;
  rows: { name: string; a: number | null; t: number | null }[];
  format?: FormatInput;
  favorable: Favorable;
  actualLabel: string;
  targetLabel: string;
  att: (r: { a: number | null; t: number | null }) => number | null;
}) {
  const { width, height, rows } = p;
  const { active, setActive, keyProps } = useActiveIndex(rows.length);
  const labelW = Math.min(Math.max(...rows.map((r) => textWidth(r.name, AXIS_FONT)), 20) + 14, width * 0.34);
  const right = width - 120;
  const max = Math.max(1e-9, ...rows.flatMap((r) => [r.a ?? 0, r.t ?? 0])) * 1.04;
  const sx = linearScale([0, max], [labelW, right]);
  const band = bandScale(rows.length, [0, height], { paddingInner: 0.42, paddingOuter: 0.2 });
  const barH = Math.min(18, band.bandwidth);
  const onMove = (e: PointerEvent<SVGRectElement>) => setActive(band.indexAt(localPoint(e).y));
  return (
    <>
      <svg width={width} height={height} role="group" aria-roledescription="chart" aria-label="Progress to target. Use arrow keys to read items." {...keyProps}>
        {rows.map((r, i) => {
          const cy = band(i) + band.bandwidth / 2;
          const y0 = cy - barH / 2;
          const a = p.att(r);
          // reaching target counts as on-target (neutral-good), so compare against 1 with a tiny tolerance
          const tone = a === null ? "neutral" : toneOf(a >= 0.9995 ? 1 : -1, p.favorable === "down" ? "down" : "up");
          return (
            <g key={i} className={`clui-mark${active !== null && active !== i ? " clui-dim" : ""}`}>
              <text x={labelW - 10} y={cy} dy="0.32em" textAnchor="end" className="clui-tick" style={{ fill: "var(--clui-ink)" }}>
                {truncate(r.name, labelW - 14, AXIS_FONT)}
              </text>
              <rect x={labelW} y={y0} width={Math.max(0, right - labelW)} height={barH} rx={3} style={{ fill: "var(--clui-grid)" }} />
              {r.a !== null && r.a > 0 && <path d={barPath(labelW, y0, sx(r.a) - labelW, barH, 3, "right")} style={{ fill: tokens.series(0) }} />}
              {r.t !== null && <line x1={sx(r.t)} x2={sx(r.t)} y1={y0 - 5} y2={y0 + barH + 5} style={{ stroke: "var(--clui-ink)" }} strokeWidth={2.5} />}
              <text x={right + 12} y={cy - 6} dy="0.32em" className="clui-label">
                {formatValue(r.a, p.format)}
              </text>
              {a !== null && (
                <text x={right + 12} y={cy + 8} dy="0.32em" className="clui-annot" style={{ fill: toneText(tone) }}>
                  {formatValue(a, { kind: "percent", decimals: 0 })} of {formatValue(r.t, p.format)}
                </text>
              )}
            </g>
          );
        })}
        <rect x={0} y={0} width={width} height={height} fill="transparent" onPointerMove={onMove} onPointerLeave={() => setActive(null)} />
      </svg>
      {active !== null && rows[active] && (
        <ChartTooltip
          x={sx(rows[active].a ?? 0)}
          y={band(active) + band.bandwidth / 2}
          width={width}
          height={height}
          data={{
            title: rows[active].name,
            rows: [
              { label: p.actualLabel, value: formatValue(rows[active].a, p.format, { context: "tooltip" }), color: tokens.series(0) },
              { label: p.targetLabel, value: formatValue(rows[active].t, p.format, { context: "tooltip" }), color: "var(--clui-ink)", shape: "line" },
              { label: "Attainment", value: formatValue(p.att(rows[active]), { kind: "percent", decimals: 1 }), strong: true },
            ],
          }}
        />
      )}
    </>
  );
}
Pro

Bullet chart

KPIs against targets and qualitative ranges: the compact replacement for gauges.

Pro

Variance chart

Actual vs plan per line item: levels and variance side by side, coloured by business direction.

KPI tile

A headline number with its comparison, direction-aware colour and an optional sparkline.