Menu

Components

Bar Chart

A bar for each number, in groups: compare amounts between things, or see how the parts of each add up.

Introduction

Bar Chart draws a bar for each number, in groups. Use it to compare amounts between things, such as sales by month or votes by option, or, stacked, to see how the parts of each add up.

  • It is drawn as SVG from your data, with no charting library to install. It is as wide as its parent and redraws when that changes.
  • Bars stand up, or lie along the side with layout="horizontal", which suits long names. Several series sit side by side in each group, or pile into one bar with isStacked.
  • Negative numbers go below the axis, and in a stack downward on their own. The outer end of each bar is rounded, as much as you set.
  • Hovering a group marks it and shows its values in a card, with a total for a stack. The legend lists the series and hides or shows each one.
  • Colors come from the theme in light and dark, the same as AreaChart. The bars grow from the axis one after the other, and not for people who prefer reduced motion.
  • The SVG is hidden from screen readers, and the same data is there as a table, under the name you give with aria-label.

It is a Client Component, so functions such as valueFormatter must be defined in a client file. It does not fetch data: pass the rows in. Each row is an object with the name of the group under the key you give as index, and a number for each series.

Installation

centerUI has no CLI or registry yet: components are copied into your project.

# bun
bun add tailwind-variants tailwind-merge clsx

# pnpm
pnpm add tailwind-variants tailwind-merge clsx

# npm
npm install tailwind-variants tailwind-merge clsx

Manual installation

Copy these files into your project and keep the paths, or adjust the imports. It uses the chart colors and the ticks of Area Chart, and the bar-chart animations from globals.css.

1. Add the shared chart parts

The chart colors --chart-1 to --chart-5 in your theme, as described for Area Chart, and these two files.

src/types/area-chart-utils.tsShow code
// The math behind AreaChart: nice axis ticks, and the paths of a line through
// points as a straight line, a smooth curve that does not overshoot, or steps.
// It knows nothing about React.

export type AreaCurve = "linear" | "monotone" | "step";

export interface Point {
  x: number;
  y: number;
}

/** One piece of a path, with where it starts so it can be walked backwards. */
type Segment =
  | { type: "L"; from: Point; to: Point }
  | { type: "C"; from: Point; c1: Point; c2: Point; to: Point };

const round = (n: number) => Math.round(n * 100) / 100;
const pt = (p: Point) => `${round(p.x)} ${round(p.y)}`;

function niceNumber(range: number, isRound: boolean) {
  const exponent = Math.floor(Math.log10(range));
  const fraction = range / 10 ** exponent;
  let nice: number;
  if (isRound) {
    nice = fraction < 1.5 ? 1 : fraction < 3 ? 2 : fraction < 7 ? 5 : 10;
  } else {
    nice = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;
  }
  return nice * 10 ** exponent;
}

/**
 * Round numbers to put on an axis, from at or below `min` to at or above
 * `max`, about `count` of them.
 */
export function niceTicks(min: number, max: number, count = 5): number[] {
  if (min === max) max = min + 1;
  const step = niceNumber((max - min) / Math.max(count - 1, 1), true);
  const start = Math.floor(min / step) * step;
  const end = Math.ceil(max / step) * step;
  const ticks: number[] = [];
  // Rounding each step keeps 0.1 + 0.2 from becoming 0.30000000000000004.
  for (let value = start; value <= end + step / 2; value += step) {
    ticks.push(Number(value.toPrecision(12)));
  }
  return ticks;
}

function monotoneTangents(points: Point[]) {
  const n = points.length;
  const slopes: number[] = [];
  for (let i = 0; i < n - 1; i++) {
    const dx = points[i + 1].x - points[i].x;
    slopes.push(dx === 0 ? 0 : (points[i + 1].y - points[i].y) / dx);
  }
  const tangents: number[] = new Array(n);
  tangents[0] = slopes[0];
  tangents[n - 1] = slopes[n - 2];
  for (let i = 1; i < n - 1; i++) {
    tangents[i] =
      slopes[i - 1] * slopes[i] <= 0 ? 0 : (slopes[i - 1] + slopes[i]) / 2;
  }
  // Keep each tangent small enough that the curve does not go past its points.
  for (let i = 0; i < n - 1; i++) {
    if (slopes[i] === 0) {
      tangents[i] = 0;
      tangents[i + 1] = 0;
      continue;
    }
    const a = tangents[i] / slopes[i];
    const b = tangents[i + 1] / slopes[i];
    const h = a * a + b * b;
    if (h > 9) {
      const t = 3 / Math.sqrt(h);
      tangents[i] = t * a * slopes[i];
      tangents[i + 1] = t * b * slopes[i];
    }
  }
  return tangents;
}

function segments(points: Point[], curve: AreaCurve): Segment[] {
  const out: Segment[] = [];
  if (curve === "monotone" && points.length > 2) {
    const tangents = monotoneTangents(points);
    for (let i = 0; i < points.length - 1; i++) {
      const from = points[i];
      const to = points[i + 1];
      const third = (to.x - from.x) / 3;
      out.push({
        type: "C",
        from,
        c1: { x: from.x + third, y: from.y + tangents[i] * third },
        c2: { x: to.x - third, y: to.y - tangents[i + 1] * third },
        to,
      });
    }
    return out;
  }
  for (let i = 0; i < points.length - 1; i++) {
    const from = points[i];
    const to = points[i + 1];
    if (curve === "step") {
      const middle = (from.x + to.x) / 2;
      const a = { x: middle, y: from.y };
      const b = { x: middle, y: to.y };
      out.push(
        { type: "L", from, to: a },
        { type: "L", from: a, to: b },
        { type: "L", from: b, to },
      );
    } else {
      out.push({ type: "L", from, to });
    }
  }
  return out;
}

const forward = (list: Segment[]) =>
  list
    .map((s) =>
      s.type === "L" ? `L${pt(s.to)}` : `C${pt(s.c1)} ${pt(s.c2)} ${pt(s.to)}`,
    )
    .join("");

// The same pieces walked from the end to the start.
const backward = (list: Segment[]) =>
  [...list]
    .reverse()
    .map((s) =>
      s.type === "L"
        ? `L${pt(s.from)}`
        : `C${pt(s.c2)} ${pt(s.c1)} ${pt(s.from)}`,
    )
    .join("");

/** The path of a line through `points`. */
export function linePath(points: Point[], curve: AreaCurve): string {
  if (points.length === 0) return "";
  if (points.length === 1) return `M${pt(points[0])}`;
  return `M${pt(points[0])}${forward(segments(points, curve))}`;
}

/**
 * The path of the shape between a line through `top` and one through `bottom`:
 * along the top, down at the end, back along the bottom, and closed. Both lines
 * are drawn with the same curve, so a stacked area sits exactly on the one
 * under it.
 */
export function areaPath(
  top: Point[],
  bottom: Point[],
  curve: AreaCurve,
): string {
  if (top.length === 0) return "";
  const last = bottom[bottom.length - 1];
  if (top.length === 1) {
    return `M${pt(top[0])}L${pt(last)}Z`;
  }
  return `M${pt(top[0])}${forward(segments(top, curve))}L${pt(last)}${backward(
    segments(bottom, curve),
  )}Z`;
}
src/types/area-chart-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for AreaChart. The chart itself is an SVG, drawn from the numbers in
// area-chart.tsx; these are the parts around it and inside it that are plain
// HTML or take their color from the theme.
export const areaChartStyles = tv({
  slots: {
    root: "flex w-full flex-col gap-3",
    plot: "relative w-full touch-pan-y",
    svg: "block overflow-visible select-none",
    axisText: "fill-muted-fg text-xs tabular-nums",
    gridLine: "stroke-border",
    cursor: "stroke-muted-fg",
    legend: "flex flex-wrap items-center gap-x-2 gap-y-1 text-sm",
    legendItem:
      "inline-flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-fg outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring aria-[pressed=false]:text-muted-fg aria-[pressed=false]:line-through",
    swatch: "size-2.5 shrink-0 rounded-[3px] transition-opacity",
    tooltip:
      "pointer-events-none absolute z-10 min-w-36 rounded-lg border bg-card px-3 py-2 text-xs text-card-fg shadow-lg",
    tooltipTitle: "mb-1.5 font-medium",
    tooltipRow: "flex items-center gap-2",
    tooltipLabel: "text-muted-fg",
    tooltipValue: "ml-auto pl-4 font-medium tabular-nums",
    live: "pointer-events-none absolute top-0 right-3 inline-flex items-center gap-1.5 rounded-full border bg-card px-2 py-0.5 text-xs font-medium text-muted-fg",
    liveDot: "size-1.5 rounded-full bg-success motion-safe:animate-pulse",
    empty: "flex items-center justify-center text-sm text-muted-fg",
  },
  variants: {
    legendPosition: {
      top: { root: "flex-col-reverse" },
      bottom: { root: "flex-col" },
    },
  },
  defaultVariants: { legendPosition: "bottom" },
});

/** The colors a series has when it is given none, in order, then again. */
export const areaChartColors = [
  "var(--chart-1)",
  "var(--chart-2)",
  "var(--chart-3)",
  "var(--chart-4)",
  "var(--chart-5)",
] as const;

2. Add the styles

src/types/bar-chart-styles.tsShow code
import { tv } from "tailwind-variants";

// Styles for BarChart. The bars are SVG, drawn from the numbers in
// bar-chart.tsx; these are the parts around and inside it that take their
// color from the theme. They match the ones of AreaChart, so two charts side by
// side look alike.
export const barChartStyles = tv({
  slots: {
    root: "flex w-full flex-col gap-3",
    plot: "relative w-full touch-pan-y",
    svg: "block overflow-visible select-none",
    axisText: "fill-muted-fg text-xs tabular-nums",
    valueText: "fill-fg text-[11px] font-medium tabular-nums",
    gridLine: "stroke-border",
    cursor: "fill-muted",
    legend: "flex flex-wrap items-center gap-x-2 gap-y-1 text-sm",
    legendItem:
      "inline-flex cursor-pointer items-center gap-2 rounded-md px-2 py-1 text-fg outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring aria-[pressed=false]:text-muted-fg aria-[pressed=false]:line-through",
    swatch: "size-2.5 shrink-0 rounded-[3px] transition-opacity",
    tooltip:
      "pointer-events-none absolute z-10 min-w-36 rounded-lg border bg-card px-3 py-2 text-xs text-card-fg shadow-lg",
    tooltipTitle: "mb-1.5 font-medium",
    tooltipRow: "flex items-center gap-2",
    tooltipLabel: "text-muted-fg",
    tooltipValue: "ml-auto pl-4 font-medium tabular-nums",
    empty: "flex items-center justify-center text-sm text-muted-fg",
  },
  variants: {
    legendPosition: {
      top: { root: "flex-col-reverse" },
      bottom: { root: "flex-col" },
    },
  },
  defaultVariants: { legendPosition: "bottom" },
});

/** The path of a bar with the corners at its outer end rounded, the end away from the axis. */
export function barPath(
  x: number,
  y: number,
  width: number,
  height: number,
  radius: number,
  side: "top" | "bottom" | "left" | "right",
): string {
  const r = Math.max(
    0,
    Math.min(
      radius,
      side === "top" || side === "bottom" ? width / 2 : height / 2,
      side === "top" || side === "bottom" ? height : width,
    ),
  );
  const f = (n: number) => Math.round(n * 100) / 100;
  const [x1, y1, x2, y2] = [x, y, x + width, y + height];
  switch (side) {
    case "top":
      return `M${f(x1)} ${f(y2)}V${f(y1 + r)}A${f(r)} ${f(r)} 0 0 1 ${f(x1 + r)} ${f(y1)}H${f(x2 - r)}A${f(r)} ${f(r)} 0 0 1 ${f(x2)} ${f(y1 + r)}V${f(y2)}Z`;
    case "bottom":
      return `M${f(x1)} ${f(y1)}V${f(y2 - r)}A${f(r)} ${f(r)} 0 0 0 ${f(x1 + r)} ${f(y2)}H${f(x2 - r)}A${f(r)} ${f(r)} 0 0 0 ${f(x2)} ${f(y2 - r)}V${f(y1)}Z`;
    case "right":
      return `M${f(x1)} ${f(y1)}H${f(x2 - r)}A${f(r)} ${f(r)} 0 0 1 ${f(x2)} ${f(y1 + r)}V${f(y2 - r)}A${f(r)} ${f(r)} 0 0 1 ${f(x2 - r)} ${f(y2)}H${f(x1)}Z`;
    case "left":
      return `M${f(x2)} ${f(y1)}H${f(x1 + r)}A${f(r)} ${f(r)} 0 0 0 ${f(x1)} ${f(y1 + r)}V${f(y2 - r)}A${f(r)} ${f(r)} 0 0 0 ${f(x1 + r)} ${f(y2)}H${f(x2)}Z`;
  }
}

3. Add the Bar Chart file

src/components/ui/bar-chart/bar-chart.tsxShow code
"use client";

import {
  type PointerEvent,
  type ReactNode,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { cn } from "@/lib/cn";
import { areaChartColors } from "@/types/area-chart-styles";
import { niceTicks } from "@/types/area-chart-utils";
import { barChartStyles, barPath } from "@/types/bar-chart-styles";

export interface BarChartSeries {
  /** The key in each row of `data` that holds this series' numbers. */
  key: string;
  /** What it is called in the legend and the tooltip. Defaults to `key`. */
  label?: string;
  /** Any CSS color, such as `var(--chart-2)` or `#3b82f6`. Defaults to the next of the theme's chart colors. */
  color?: string;
}

export interface BarChartProps<T extends Record<string, unknown>> {
  /** One row per group of bars: `{ month: "Jan", desktop: 186, mobile: 80 }`. */
  data: T[];
  /** The key of the value that names each group, such as `month`. */
  index: keyof T & string;
  /** The bars to draw in each group, one per key of the rows that holds numbers. */
  series: BarChartSeries[];
  /**
   * The direction of the bars: `vertical` stand on the bottom and rise,
   * `horizontal` lie along the left and reach out to the right, which suits
   * long names. Defaults to `vertical`.
   */
  layout?: "vertical" | "horizontal";
  /** Pile the series of a group into one bar, so its length is their total, instead of side by side. */
  isStacked?: boolean;
  /** The lines behind the bars: at the numbers of the value axis, at each group, both, or none. Defaults to `value`. */
  grid?: "value" | "index" | "both" | "none";
  /** The names of the groups, along the bottom (vertical) or the left (horizontal). Defaults to `true`. */
  showIndexAxis?: boolean;
  /** The numbers, along the left (vertical) or the bottom (horizontal). Defaults to `true`. */
  showValueAxis?: boolean;
  /** The card that follows the pointer and shows the values of the group under it. Defaults to `true`. */
  showTooltip?: boolean;
  /** The list of series, which also hides and shows them. Defaults to `true` when there is more than one. */
  showLegend?: boolean;
  legendPosition?: "top" | "bottom";
  /** Write the number at the end of each bar. Not for stacked bars. Defaults to `false`. */
  showValues?: boolean;
  /** How round the outer end of a bar is, in pixels. Defaults to 4. */
  radius?: number;
  /** The space between the bars of a group, in pixels. Defaults to 4. */
  barGap?: number;
  /** How much of the room of each group is left empty around its bars, from 0 to 0.9. Defaults to 0.3. */
  categoryGap?: number;
  /** The widest a bar gets, in pixels. Defaults to 48. */
  maxBarSize?: number;
  /** The height of the plot in pixels. The width is that of the parent. Defaults to 280. */
  height?: number;
  /** Where a number is shown, on the axis and in the tooltip: `(v) => "$" + v`. */
  valueFormatter?: (value: number) => string;
  /** Where the name of a group is shown, on the axis and the tooltip's title. */
  indexFormatter?: (value: string) => string;
  /** About how many numbers on the value axis. Defaults to 5. */
  tickCount?: number;
  /** The lowest number of the value axis. Defaults to 0, or lower if the data is. */
  minValue?: number;
  /** The highest number of the value axis. Defaults to a round number above the data. */
  maxValue?: number;
  /** Names the chart for screen readers. A table of the data is there too. */
  "aria-label": string;
  className?: string;
}

const CHAR = 6.6;

type Row = Record<string, unknown>;

const toNumber = (value: unknown) => {
  const n = Number(value);
  return Number.isFinite(n) ? n : 0;
};

const defaultValueFormatter = (value: number) =>
  new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(value);

const shorten = (text: string, chars: number) =>
  text.length > chars ? `${text.slice(0, Math.max(chars - 1, 1))}…` : text;

/**
 * A bar chart: a bar for each number, in groups. Use it to compare amounts
 * between things, such as sales by month or votes by option, or with
 * `isStacked` to see how the parts of each add up.
 *
 * The bars stand up or, with `layout="horizontal"`, lie along the side, which
 * suits long names. It is drawn as SVG from your data, with no charting library,
 * as wide as its parent. The tooltip shows the values of the group under the
 * pointer, the legend hides and shows series, colors follow the theme in light
 * and dark, and screen readers get the data as a table.
 *
 * @example
 * <BarChart
 *   aria-label="Sales by month"
 *   data={[{ month: "Jan", sales: 186 }, { month: "Feb", sales: 305 }]}
 *   index="month"
 *   series={[{ key: "sales", label: "Sales" }]}
 * />
 */
export function BarChart<T extends Row>({
  data,
  index,
  series,
  layout = "vertical",
  isStacked = false,
  grid = "value",
  showIndexAxis = true,
  showValueAxis = true,
  showTooltip = true,
  showLegend,
  legendPosition,
  showValues = false,
  radius = 4,
  barGap = 4,
  categoryGap = 0.3,
  maxBarSize = 48,
  height = 280,
  valueFormatter = defaultValueFormatter,
  indexFormatter = (value) => value,
  tickCount = 5,
  minValue,
  maxValue,
  "aria-label": ariaLabel,
  className,
}: BarChartProps<T>) {
  const styles = barChartStyles({ legendPosition });
  const plot = useRef<HTMLDivElement>(null);
  const [width, setWidth] = useState(0);
  const [pointer, setPointer] = useState<{
    x: number;
    y: number;
    index: number;
  } | null>(null);
  const [hidden, setHidden] = useState<string[]>([]);
  const isH = layout === "horizontal";

  useLayoutEffect(() => {
    const el = plot.current;
    if (!el) return;
    setWidth(el.clientWidth);
    const observer = new ResizeObserver(([entry]) =>
      setWidth(entry.contentRect.width),
    );
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  const all = useMemo(
    () =>
      series.map((s, i) => ({
        key: s.key,
        label: s.label ?? s.key,
        color: s.color ?? areaChartColors[i % areaChartColors.length],
      })),
    [series],
  );
  const visible = all.filter((s) => !hidden.includes(s.key));
  const hasLegend = showLegend ?? all.length > 1;
  const count = data.length;

  // The numbers of each visible series, and where each bar starts and ends
  // along the value axis: at zero, or, stacked, on top of the bars before it,
  // with the ones below zero stacked downward on their own.
  const layers = useMemo(() => {
    const up = new Array<number>(count).fill(0);
    const down = new Array<number>(count).fill(0);
    return visible.map((s) => {
      const values = data.map((row) => toNumber(row[s.key]));
      const base = values.map((v, i) =>
        isStacked ? (v >= 0 ? up[i] : down[i]) : 0,
      );
      const top = values.map((v, i) => base[i] + v);
      if (isStacked) {
        values.forEach((v, i) => {
          if (v >= 0) up[i] += v;
          else down[i] += v;
        });
      }
      return { ...s, values, base, top };
    });
  }, [visible, data, count, isStacked]);

  // In a stack only the last bar on each side is round at its end.
  const outermost = useMemo(() => {
    const result = new Map<string, boolean>();
    for (let i = 0; i < count; i++) {
      let lastUp = -1;
      let lastDown = -1;
      layers.forEach((layer, li) => {
        if (layer.values[i] > 0) lastUp = li;
        if (layer.values[i] < 0) lastDown = li;
      });
      layers.forEach((layer, li) => {
        result.set(`${layer.key}:${i}`, li === lastUp || li === lastDown);
      });
    }
    return result;
  }, [layers, count]);

  const ticks = useMemo(() => {
    let low = 0;
    let high = 0;
    for (const layer of layers) {
      for (let i = 0; i < count; i++) {
        low = Math.min(low, layer.top[i], layer.base[i]);
        high = Math.max(high, layer.top[i], layer.base[i]);
      }
    }
    const lowest = minValue ?? low;
    const highest = maxValue ?? high;
    return niceTicks(
      lowest,
      highest === lowest ? lowest + 1 : highest,
      tickCount,
    );
  }, [layers, count, minValue, maxValue, tickCount]);
  const vMin = minValue ?? ticks[0];
  const vMax = maxValue ?? ticks[ticks.length - 1];

  const valueLabels = ticks.map((t) => valueFormatter(t));
  const names = data.map((row) => indexFormatter(String(row[index] ?? "")));
  const widestName = Math.max(1, ...names.map((n) => n.length));
  const widestValue = Math.max(...valueLabels.map((l) => l.length));

  // The room the axes take. Along the side, the names of the groups can be long,
  // so they get at most a third of the width and are cut short after that.
  const sideAxis = isH
    ? showIndexAxis
      ? Math.min(Math.ceil(widestName * CHAR) + 12, Math.max(width / 3, 48))
      : 0
    : showValueAxis
      ? Math.ceil(widestValue * CHAR) + 12
      : 0;
  const bottomAxis = isH ? showValueAxis : showIndexAxis;
  const margin = {
    top: 10,
    right: 16,
    bottom: bottomAxis ? 30 : 10,
    left: sideAxis || 12,
  };
  const innerW = Math.max(width - margin.left - margin.right, 0);
  const innerH = Math.max(height - margin.top - margin.bottom, 0);

  // Positions. `along` runs across the groups, `valueAt` along the numbers.
  const bandLength = isH ? innerH : innerW;
  const band = count > 0 ? bandLength / count : 0;
  const bandStart = (i: number) => (isH ? margin.top : margin.left) + i * band;
  const valueAt = (v: number) => {
    const t = (v - vMin) / (vMax - vMin || 1);
    return isH ? margin.left + t * innerW : margin.top + innerH - t * innerH;
  };

  const per = isStacked ? 1 : Math.max(layers.length, 1);
  const group = Math.max(
    Math.min(
      band * (1 - Math.min(Math.max(categoryGap, 0), 0.9)),
      maxBarSize * per,
    ),
    0,
  );
  const barSize = Math.max((group - barGap * (per - 1)) / per, 1);
  const barStart = (i: number, li: number) =>
    bandStart(i) +
    (band - group) / 2 +
    (isStacked ? 0 : li * (barSize + barGap));

  // Which names to write along the bottom so they do not run into each other,
  // or along the side when the bars are too thin for every name.
  const every = isH
    ? Math.max(1, Math.ceil(16 / (band || 1)))
    : Math.max(
        1,
        Math.ceil(
          count / Math.max(2, Math.floor(innerW / (widestName * CHAR + 16))),
        ),
      );

  function moveTo(event: PointerEvent<HTMLDivElement>) {
    if (!showTooltip || count === 0) return;
    const box = event.currentTarget.getBoundingClientRect();
    const x = event.clientX - box.left;
    const y = event.clientY - box.top;
    const along = isH ? y - margin.top : x - margin.left;
    const i = Math.min(Math.max(Math.floor(along / (band || 1)), 0), count - 1);
    setPointer({ x, y, index: i });
  }

  function toggle(key: string) {
    setHidden((current) =>
      current.includes(key)
        ? current.filter((k) => k !== key)
        : visible.length > 1
          ? [...current, key]
          : current,
    );
  }

  const active = pointer?.index ?? null;
  const flip = pointer !== null && pointer.x > width / 2;

  let body: ReactNode = null;
  if (count === 0) {
    body = (
      <div className={styles.empty()} style={{ height }}>
        No data
      </div>
    );
  } else if (width > 0) {
    body = (
      <svg
        width={width}
        height={height}
        viewBox={`0 0 ${width} ${height}`}
        aria-hidden="true"
        className={styles.svg()}
      >
        {grid === "value" || grid === "both"
          ? ticks.map((t) => {
              const at = valueAt(t);
              return (
                <line
                  key={t}
                  className={styles.gridLine()}
                  x1={isH ? at : margin.left}
                  x2={isH ? at : margin.left + innerW}
                  y1={isH ? margin.top : at}
                  y2={isH ? margin.top + innerH : at}
                  strokeDasharray="3 4"
                />
              );
            })
          : null}
        {grid === "index" || grid === "both"
          ? data.map((_, i) => {
              const at = bandStart(i) + band / 2;
              return (
                <line
                  // biome-ignore lint/suspicious/noArrayIndexKey: the groups are the positions
                  key={i}
                  className={styles.gridLine()}
                  x1={isH ? margin.left : at}
                  x2={isH ? margin.left + innerW : at}
                  y1={isH ? at : margin.top}
                  y2={isH ? at : margin.top + innerH}
                  strokeDasharray="3 4"
                />
              );
            })
          : null}

        {active !== null ? (
          <rect
            className={styles.cursor()}
            fillOpacity={0.6}
            rx={6}
            x={isH ? margin.left : bandStart(active)}
            y={isH ? bandStart(active) : margin.top}
            width={isH ? innerW : band}
            height={isH ? band : innerH}
          />
        ) : null}

        {showValueAxis
          ? ticks.map((t, i) => {
              const at = valueAt(t);
              return (
                <text
                  key={t}
                  className={styles.axisText()}
                  x={isH ? at : margin.left - 8}
                  y={isH ? height - margin.bottom + 20 : at}
                  textAnchor={isH ? "middle" : "end"}
                  dominantBaseline={isH ? undefined : "central"}
                >
                  {valueLabels[i]}
                </text>
              );
            })
          : null}
        {showIndexAxis
          ? names.map((name, i) => {
              if (i % every !== 0) return null;
              const at = bandStart(i) + band / 2;
              return (
                <text
                  // biome-ignore lint/suspicious/noArrayIndexKey: the groups are the positions
                  key={i}
                  className={styles.axisText()}
                  x={isH ? margin.left - 8 : at}
                  y={isH ? at : height - margin.bottom + 20}
                  textAnchor={isH ? "end" : "middle"}
                  dominantBaseline={isH ? "central" : undefined}
                >
                  {isH
                    ? shorten(name, Math.floor((margin.left - 12) / CHAR))
                    : name}
                </text>
              );
            })
          : null}

        {layers.map((layer, li) =>
          layer.values.map((value, i) => {
            const a = valueAt(layer.base[i]);
            const b = valueAt(layer.top[i]);
            const length = Math.abs(a - b);
            if (length < 0.5) return null;
            const start = barStart(i, li);
            const along = Math.min(a, b);
            const round = !isStacked || outermost.get(`${layer.key}:${i}`);
            const side = isH
              ? value >= 0
                ? "right"
                : "left"
              : value >= 0
                ? "top"
                : "bottom";
            const [x, y, w, h] = isH
              ? [along, start, length, barSize]
              : [start, along, barSize, length];
            const end = value >= 0 ? Math.max(a, b) : Math.min(a, b);
            const showLabel =
              showValues &&
              !isStacked &&
              (isH || barSize >= valueFormatter(value).length * 6.2 - 2);
            return (
              <g key={`${layer.key}-${i}`}>
                <path
                  className={isH ? "bar-chart-grow-x" : "bar-chart-grow-y"}
                  style={{ animationDelay: `${i * 40}ms` }}
                  d={barPath(x, y, w, h, round ? radius : 0, side)}
                  fill={layer.color}
                />
                {showLabel ? (
                  <text
                    className={cn(styles.valueText(), "bar-chart-fade")}
                    x={isH ? end + (value >= 0 ? 6 : -6) : start + barSize / 2}
                    y={isH ? start + barSize / 2 : end + (value >= 0 ? -6 : 14)}
                    textAnchor={isH ? (value >= 0 ? "start" : "end") : "middle"}
                    dominantBaseline={isH ? "central" : undefined}
                  >
                    {valueFormatter(value)}
                  </text>
                ) : null}
              </g>
            );
          }),
        )}
      </svg>
    );
  } else {
    body = <div style={{ height }} />;
  }

  return (
    <figure
      aria-label={ariaLabel}
      className={cn(styles.root(), "m-0", className)}
    >
      <div
        ref={plot}
        className={styles.plot()}
        onPointerMove={moveTo}
        onPointerDown={moveTo}
        onPointerLeave={() => setPointer(null)}
      >
        {body}
        {showTooltip && pointer !== null && active !== null && count > 0 ? (
          <div
            className={styles.tooltip()}
            style={{
              top: Math.max(0, Math.min(pointer.y - 16, height - 100)),
              left: pointer.x,
              transform: `translateX(${flip ? "calc(-100% - 14px)" : "14px"})`,
            }}
          >
            <p className={cn(styles.tooltipTitle(), "m-0")}>{names[active]}</p>
            <div className="flex flex-col gap-1">
              {layers.map((layer) => (
                <div key={layer.key} className={styles.tooltipRow()}>
                  <span
                    aria-hidden="true"
                    className={styles.swatch()}
                    style={{ background: layer.color }}
                  />
                  <span className={styles.tooltipLabel()}>{layer.label}</span>
                  <span className={styles.tooltipValue()}>
                    {valueFormatter(layer.values[active])}
                  </span>
                </div>
              ))}
              {isStacked && layers.length > 1 ? (
                <div
                  className={cn(styles.tooltipRow(), "mt-1 border-t pt-1.5")}
                >
                  <span className={styles.tooltipLabel()}>Total</span>
                  <span className={styles.tooltipValue()}>
                    {valueFormatter(
                      layers.reduce((sum, l) => sum + l.values[active], 0),
                    )}
                  </span>
                </div>
              ) : null}
            </div>
          </div>
        ) : null}
      </div>

      {hasLegend ? (
        <div className={styles.legend()}>
          {all.map((s) => {
            const shown = !hidden.includes(s.key);
            return (
              <button
                key={s.key}
                type="button"
                aria-pressed={shown}
                onClick={() => toggle(s.key)}
                className={styles.legendItem()}
              >
                <span
                  aria-hidden="true"
                  className={cn(styles.swatch(), !shown && "opacity-40")}
                  style={{ background: s.color }}
                />
                {s.label}
              </button>
            );
          })}
        </div>
      ) : null}

      <table className="sr-only">
        <caption>{ariaLabel}</caption>
        <thead>
          <tr>
            <th scope="col">{index}</th>
            {all.map((s) => (
              <th key={s.key} scope="col">
                {s.label}
              </th>
            ))}
          </tr>
        </thead>
        <tbody>
          {data.map((row, i) => (
            // biome-ignore lint/suspicious/noArrayIndexKey: rows have no id of their own
            <tr key={i}>
              <th scope="row">{names[i]}</th>
              {all.map((s) => (
                <td key={s.key}>{valueFormatter(toNumber(row[s.key]))}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </figure>
  );
}

4. Use it

import { BarChart } from "@/components/ui/bar-chart/bar-chart";

Anatomy

An SVG with a tooltip over it, and a legend under it.

<BarChart
  aria-label="Sales by month"
  data={[{ month: "Jan", desktop: 186, mobile: 80 }, ...]}
  index="month"
  series={[
    { key: "desktop", label: "Desktop" },
    { key: "mobile", label: "Mobile" },
  ]}
/>
PartRendered asNotes
PlotsvgThe bars, the grid and the axes, drawn from the data at the width of the parent.
BarpathOne per number. The end away from the axis is rounded.
Axes and gridtext, lineRound numbers on one side, the name of each group on the other, and the lines behind.
TooltipdivA card that follows the pointer with the values of the group under it, and a band that marks the group.
LegendbuttonOne button per series. Pressing it hides or shows the series.
Data tabletable, sr-onlyThe same data as a table for screen readers. The SVG is hidden from them.

Examples

Usage

Move the pointer over the chart to see the values.

Desktop sales by month
monthDesktop
Jan186
Feb305
Mar237
Apr273
May209
Jun314

Grouped

Add a series for each key. The bars of a group sit side by side, and with more than one series the legend shows.

Sales by month and device
monthDesktopMobile
Jan18680
Feb305200
Mar237120
Apr273190
May209130
Jun314240

Stacked

isStacked piles the series of a group into one bar, so its length is their total, and the tooltip adds a Total row.

Stacked sales by month and device
monthDesktopMobileTablet
Jan1868032
Feb30520048
Mar23712041
Apr27319062
May20913055
Jun31424070

Horizontal

Bars that lie along the side, for long names or many groups. It works stacked too.

Votes by programming language
nameVotes
TypeScript4,820
Python4,315
Rust2,980
Go2,410
Kotlin1,670
Elixir940
Stacked sales by month and device, horizontal
monthDesktopMobileTablet
Jan1868032
Feb30520048
Mar23712041
Apr27319062
May20913055
Jun31424070

Numbers on the bars

showValues writes the number at the end of each bar, so the value axis and the grid can go. A number that does not fit on a narrow bar is left out, and stacked bars do not have them.

Desktop sales with the numbers on the bars
monthDesktop
Jan186
Feb305
Mar237
Apr273
May209
Jun314

Negative numbers

Bars below zero hang down from the axis, and the axis stretches to hold them.

Profit by quarter, with losses
quarterProfit
Q1$42k
Q2-$18k
Q3$65k
Q4-$7k
Q5$28k

Rounded ends

radius rounds the end of a bar away from the axis, in pixels. It never goes past half the width of the bar.

radius 0

Desktop sales, radius 0
monthDesktop
Jan186
Feb305
Mar237
Apr273
May209
Jun314

radius 6

Desktop sales, radius 6
monthDesktop
Jan186
Feb305
Mar237
Apr273
May209
Jun314

radius 24

Desktop sales, radius 24
monthDesktop
Jan186
Feb305
Mar237
Apr273
May209
Jun314

Width and spacing

categoryGap is how much of each group's room is left empty, barGap the space between the bars of a group, and maxBarSize how wide a bar gets.

Wide bars, no gap

Sales with wide bars
monthDesktopMobile
Jan18680
Feb305200
Mar237120
Apr273190
May209130
Jun314240

Thin bars, more room

Sales with thin bars
monthDesktopMobile
Jan18680
Feb305200
Mar237120
Apr273190
May209130
Jun314240

Grid and axes

The grid is at the numbers of the value axis by default, or at each group, both, or none. Each axis can be turned off.

Desktop sales with a full grid
monthDesktop
Jan186
Feb305
Mar237
Apr273
May209
Jun314

Formatting values

valueFormatter writes the numbers on the axis, the tooltip and the bars, and indexFormatter the names of the groups.

Revenue by month
monthRevenue
Jan 2026$24,180
Feb 2026$39,650
Mar 2026$30,810
Apr 2026$35,490
May 2026$27,170
Jun 2026$40,820

Colors

A series takes the next chart color of the theme. Give color to choose one, any CSS color or a theme token.

Sales in custom colors
monthDesktopMobile
Jan18680
Feb305200
Mar237120
Apr273190
May209130
Jun314240

Legend

Put the legend above the chart, or turn it off. One series has no legend unless showLegend is set.

Sales with the legend on top
monthDesktopMobileTablet
Jan1868032
Feb30520048
Mar23712041
Apr27319062
May20913055
Jun31424070

Range and height

Fix the ends of the value axis with minValue and maxValue, choose how many numbers it has with tickCount, and set the height in pixels.

Desktop sales on a fixed scale
monthDesktop
Jan186
Feb305
Mar237
Apr273
May209
Jun314

No data

With no rows it says so instead of drawing an empty plot.

No data
No sales yet
monthDesktop

Component API

BarChart takes the props below, and each item of series takes the second table.

PropTypeDefault
dataRecord<string, unknown>[]-
indexstring-
seriesBarChartSeries[]-
aria-labelstring-
layout"vertical" | "horizontal""vertical"
isStackedbooleanfalse
grid"value" | "index" | "both" | "none""value"
showIndexAxisbooleantrue
showValueAxisbooleantrue
showTooltipbooleantrue
showLegendbooleantrue if more than one series
legendPosition"top" | "bottom""bottom"
showValuesbooleanfalse
radiusnumber (px)4
barGapnumber (px)4
categoryGapnumber (0 to 0.9)0.3
maxBarSizenumber (px)48
heightnumber (px)280
valueFormatter(value: number) => stringnumber with grouping
indexFormatter(value: string) => stringthe value
tickCountnumber5
minValuenumber0, or lower if the data is
maxValuenumbera round number above the data
classNamestring-

BarChartSeries

PropTypeDefault
keystring-
labelstringkey
colorstringthe next --chart-N