Menu

Components

Pie Chart

A circle cut into slices, each as big as its share of the total: how a whole is divided between a few parts.

Introduction

Pie Chart cuts a circle into slices, each as big as its share of the total. Use it to show how a whole is divided between a few parts, such as visitors by browser or spending by category.

  • It is drawn as SVG from your data, with no charting library to install, and scales to the width it is given, up to size.
  • A whole pie, or a donut with a hole that holds the total. Hovering a slice moves it out, dims the others, and shows its number and name in the hole, and in a tooltip with its share.
  • Gaps between the slices, round corners, the order of the slices and where the first one starts are all set with props. The share, number or name can be written on the slices that are big enough.
  • The legend lists every row with its number, lights up its slice when you point at it, and hides or shows a slice when you press it, so the rest re-divide the circle.
  • Colors come from the theme in light and dark, and the chart turns in as it appears, 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.

A pie is best with five or six slices and numbers that are not close to each other. With more, or when you want to compare the sizes exactly, use BarChart or BarList. It is a Client Component, so functions such as valueFormatter must be defined in a client file. Each row is an object with the name of the slice under the key you give as index and its number under value. Zero and negative numbers make no slice.

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 of the theme, described for Area Chart, and the pie-chart animation from globals.css.

1. Add the chart colors

The areaChartColors list, which points at --chart-1 to --chart-5 in your theme.

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 geometry

src/types/pie-chart-utils.tsShow code
// The geometry of PieChart: where a point is at an angle on a circle, and the
// path of a slice. Angles are in degrees, 0 at the top and growing clockwise.
// It knows nothing about React.

const RAD = Math.PI / 180;
const round = (n: number) => Math.round(n * 100) / 100;

/** The point at `angle` degrees on the circle of `radius` around (`cx`, `cy`). */
export function polar(cx: number, cy: number, radius: number, angle: number) {
  const a = (angle - 90) * RAD;
  return { x: cx + radius * Math.cos(a), y: cy + radius * Math.sin(a) };
}

/**
 * The path of a slice from `start` to `end` degrees, between the circles of
 * `inner` and `outer` radius. With an inner radius of 0 it is a wedge that
 * comes to the center. A slice of the whole circle is drawn as two halves,
 * because one arc cannot start and end at the same point.
 */
export function slicePath(
  cx: number,
  cy: number,
  inner: number,
  outer: number,
  start: number,
  end: number,
): string {
  if (end - start >= 359.99) {
    const half = start + 180;
    const ring = `${arc(cx, cy, outer, start, half)}${arc(cx, cy, outer, half, start + 360, false)}`;
    if (inner <= 0) return `${ring}Z`;
    return `${ring}Z${arc(cx, cy, inner, start, half, true, true)}${arc(cx, cy, inner, half, start + 360, false, true)}Z`;
  }
  const large = end - start > 180 ? 1 : 0;
  const o0 = polar(cx, cy, outer, start);
  const o1 = polar(cx, cy, outer, end);
  const outerArc = `M${round(o0.x)} ${round(o0.y)}A${round(outer)} ${round(outer)} 0 ${large} 1 ${round(o1.x)} ${round(o1.y)}`;
  if (inner <= 0) return `${outerArc}L${round(cx)} ${round(cy)}Z`;
  const i1 = polar(cx, cy, inner, end);
  const i0 = polar(cx, cy, inner, start);
  return `${outerArc}L${round(i1.x)} ${round(i1.y)}A${round(inner)} ${round(inner)} 0 ${large} 0 ${round(i0.x)} ${round(i0.y)}Z`;
}

function arc(
  cx: number,
  cy: number,
  radius: number,
  from: number,
  to: number,
  move = true,
  reverse = false,
) {
  const a = polar(cx, cy, radius, reverse ? to : from);
  const b = polar(cx, cy, radius, reverse ? from : to);
  return `${move ? `M${round(a.x)} ${round(a.y)}` : ""}A${round(radius)} ${round(radius)} 0 0 ${reverse ? 0 : 1} ${round(b.x)} ${round(b.y)}`;
}

export const toDegrees = (radians: number) => radians / RAD;

/**
 * The path of an arc of the circle of `radius` from `start` to `end` degrees,
 * for drawing with a stroke rather than a fill. An arc of the whole circle is
 * drawn as two halves, because one arc cannot start and end at the same point.
 */
export function arcPath(
  cx: number,
  cy: number,
  radius: number,
  start: number,
  end: number,
): string {
  const f = (n: number) => Math.round(n * 100) / 100;
  if (end - start >= 359.99) {
    const a = polar(cx, cy, radius, start);
    const b = polar(cx, cy, radius, start + 180);
    return `M${f(a.x)} ${f(a.y)}A${f(radius)} ${f(radius)} 0 0 1 ${f(b.x)} ${f(b.y)}A${f(radius)} ${f(radius)} 0 0 1 ${f(a.x)} ${f(a.y)}`;
  }
  const from = polar(cx, cy, radius, start);
  const to = polar(cx, cy, radius, end);
  const large = end - start > 180 ? 1 : 0;
  return `M${f(from.x)} ${f(from.y)}A${f(radius)} ${f(radius)} 0 ${large} 1 ${f(to.x)} ${f(to.y)}`;
}

3. Add the styles

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

// Styles for PieChart. The chart is SVG in a fixed coordinate space that scales
// to the width it is given; these are the parts around it and the text inside
// it that take their color from the theme. They match the other charts.
export const pieChartStyles = tv({
  slots: {
    root: "flex w-full items-center justify-center gap-6",
    plot: "relative w-full shrink-0",
    svg: "block h-auto w-full overflow-visible select-none",
    slice:
      "cursor-default outline-none transition-[opacity,transform] duration-200 ease-out motion-reduce:transition-none",
    sliceLabel:
      "pointer-events-none fill-bg text-[11px] font-semibold tabular-nums",
    centerValue: "fill-fg font-semibold tabular-nums",
    centerLabel: "fill-muted-fg",
    legend: "flex flex-wrap 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",
    legendValue: "text-muted-fg tabular-nums",
    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",
    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: {
      bottom: { root: "flex-col", legend: "justify-center" },
      right: {
        root: "flex-col sm:flex-row",
        legend: "flex-col gap-y-0.5",
      },
      left: {
        root: "flex-col sm:flex-row-reverse",
        legend: "flex-col gap-y-0.5",
      },
      top: { root: "flex-col-reverse", legend: "justify-center" },
    },
  },
  defaultVariants: { legendPosition: "bottom" },
});

4. Add the Pie Chart file

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

import { type PointerEvent, useMemo, useRef, useState } from "react";
import { cn } from "@/lib/cn";
import { areaChartColors } from "@/types/area-chart-styles";
import { pieChartStyles } from "@/types/pie-chart-styles";
import { polar, slicePath, toDegrees } from "@/types/pie-chart-utils";

export interface PieChartProps<T extends Record<string, unknown>> {
  /** One row per slice: `{ browser: "Chrome", visitors: 275 }`. */
  data: T[];
  /** The key of the value that names each slice, such as `browser`. */
  index: keyof T & string;
  /** The key of the number of each slice, such as `visitors`. The size of the slice follows it. */
  value: keyof T & string;
  /**
   * A whole pie, or a `donut` with a hole in the middle, which holds the total
   * and reads better with a few slices. Defaults to `pie`.
   */
  variant?: "pie" | "donut";
  /** How big the hole of a donut is, as a share of the radius from 0 to 0.9. Defaults to 0.62. Not used by a pie. */
  innerRadius?: number;
  /** The colors of the slices in order, any CSS colors. Defaults to the theme's chart colors, then again. */
  colors?: string[];
  /** The order of the slices: as given, biggest first, or smallest first. Defaults to `none`. */
  sortOrder?: "none" | "descending" | "ascending";
  /** Where the first slice starts, in degrees clockwise from the top. Defaults to 0. */
  startAngle?: number;
  /** The space between slices, in degrees. Defaults to 1.5. */
  gap?: number;
  /** How round the corners of the slices are, in units of the 240 wide drawing. Defaults to 0. */
  cornerRadius?: number;
  /** What to write on each slice big enough to hold it. Defaults to `none`. */
  showLabels?: "none" | "percent" | "value" | "name";
  /** The card that follows the pointer with the name, value and share of the slice. Defaults to `true`. */
  showTooltip?: boolean;
  /** The list of slices, which also hides and shows them. Defaults to `true`. */
  showLegend?: boolean;
  legendPosition?: "top" | "bottom" | "left" | "right";
  /** In the hole of a donut, the total. Defaults to `true`. */
  showTotal?: boolean;
  /** What it says under the total. Defaults to "Total". */
  totalLabel?: string;
  /** Where a number is shown, in the tooltip, the legend and the middle: `(v) => "$" + v`. */
  valueFormatter?: (value: number) => string;
  /** Where the name of a slice is shown. */
  indexFormatter?: (value: string) => string;
  /** How wide the chart is at most, in pixels. It gets narrower when its parent is. Defaults to 260. */
  size?: number;
  /** Names the chart for screen readers. A table of the data is there too. */
  "aria-label": string;
  className?: string;
}

type Row = Record<string, unknown>;

// The drawing is in a space of SIZE units, whatever size it is shown at.
const SIZE = 240;
const CENTER = SIZE / 2;
const RADIUS = SIZE / 2 - 10;
const POP = 6;

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

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

const percentFormatter = new Intl.NumberFormat("en-US", {
  maximumFractionDigits: 1,
});

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

/**
 * A pie chart: a circle cut into slices, each as big as its share of the
 * total. Use it to show how a whole is divided between a few parts, such as
 * visitors by browser or spending by category. With `variant="donut"` there is
 * a hole in the middle that holds the total, and the slice under the pointer.
 *
 * It is drawn as SVG from your data, with no charting library, and scales to
 * the width it is given. The tooltip and the legend show each slice's number
 * and share, the legend hides and shows slices, colors follow the theme in
 * light and dark, and screen readers get the data as a table.
 *
 * Keep it to five or six slices: more than that is easier to read as a bar
 * chart or a `BarList`.
 *
 * @example
 * <PieChart
 *   aria-label="Visitors by browser"
 *   data={[{ browser: "Chrome", visitors: 275 }, { browser: "Safari", visitors: 200 }]}
 *   index="browser"
 *   value="visitors"
 *   variant="donut"
 * />
 */
export function PieChart<T extends Row>({
  data,
  index,
  value,
  variant = "pie",
  innerRadius = 0.62,
  colors,
  sortOrder = "none",
  startAngle = 0,
  gap = 1.5,
  cornerRadius = 0,
  showLabels = "none",
  showTooltip = true,
  showLegend = true,
  legendPosition = "bottom",
  showTotal = true,
  totalLabel = "Total",
  valueFormatter = defaultValueFormatter,
  indexFormatter = (name) => name,
  size = 260,
  "aria-label": ariaLabel,
  className,
}: PieChartProps<T>) {
  const styles = pieChartStyles({ legendPosition });
  const plot = useRef<HTMLDivElement>(null);
  const [hidden, setHidden] = useState<string[]>([]);
  const [active, setActive] = useState<string | null>(null);
  const [pointer, setPointer] = useState<{ x: number; y: number } | null>(null);
  const isDonut = variant === "donut";
  const inner = isDonut ? RADIUS * Math.min(Math.max(innerRadius, 0), 0.9) : 0;

  // Every row, with the color it keeps whether or not the others are hidden.
  const items = useMemo(() => {
    const palette = colors?.length ? colors : areaChartColors;
    return data.map((row, i) => {
      const name = String(row[index] ?? "");
      return {
        id: `${i}`,
        name,
        label: indexFormatter(name),
        amount: toNumber(row[value]),
        color: palette[i % palette.length],
      };
    });
  }, [data, index, value, colors, indexFormatter]);

  const total = items.reduce(
    (sum, item) => (hidden.includes(item.id) ? sum : sum + item.amount),
    0,
  );

  // The visible slices with where each starts and ends.
  const slices = useMemo(() => {
    const shown = items.filter(
      (item) => !hidden.includes(item.id) && item.amount > 0,
    );
    if (sortOrder !== "none") {
      shown.sort((a, b) =>
        sortOrder === "descending" ? b.amount - a.amount : a.amount - b.amount,
      );
    }
    const sum = shown.reduce((s, item) => s + item.amount, 0);
    let from = startAngle;
    return shown.map((item) => {
      const span = (item.amount / sum) * 360;
      const start = from;
      from += span;
      return {
        ...item,
        start,
        end: from,
        span,
        share: (item.amount / sum) * 100,
      };
    });
  }, [items, hidden, sortOrder, startAngle]);

  function slicePathFor(start: number, end: number, span: number) {
    // A gap between slices, unless there is only one, or the slice is too thin.
    const g = slices.length > 1 && span > gap * 2 ? gap / 2 : 0;
    // Round corners: draw the slice smaller, and outline it in its own color
    // with round joins, which grows it back with round corners.
    const rounded = cornerRadius > 0 && span > 8 ? cornerRadius : 0;
    const outer = RADIUS - rounded;
    const inside = inner > 0 ? inner + rounded : 0;
    const a0 = start + g + (rounded ? toDegrees(rounded / outer) : 0);
    const a1 = end - g - (rounded ? toDegrees(rounded / outer) : 0);
    if (a1 <= a0) return { d: "", rounded: 0 };
    const i0 =
      inside > 0 && rounded
        ? toDegrees(rounded / inside) - toDegrees(rounded / outer)
        : 0;
    return {
      d: slicePath(CENTER, CENTER, inside, outer, a0 + i0, a1 - i0),
      rounded,
    };
  }

  function track(event: PointerEvent, id: string) {
    const box = plot.current?.getBoundingClientRect();
    if (!box) return;
    setActive(id);
    setPointer({ x: event.clientX - box.left, y: event.clientY - box.top });
  }

  function leave() {
    setActive(null);
    setPointer(null);
  }

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

  const current = slices.find((s) => s.id === active) ?? null;
  const hasData = items.some((item) => item.amount > 0);
  const flip =
    pointer !== null &&
    plot.current !== null &&
    pointer.x > plot.current.clientWidth / 2;
  const valueSize = Math.min(30, Math.max(inner * 0.34, 14));

  return (
    <figure
      aria-label={ariaLabel}
      className={cn(styles.root(), "m-0", className)}
    >
      {hasData ? (
        <div ref={plot} className={styles.plot()} style={{ maxWidth: size }}>
          <svg
            viewBox={`0 0 ${SIZE} ${SIZE}`}
            aria-hidden="true"
            className={styles.svg()}
          >
            <g
              className="pie-chart-in"
              style={{ transformOrigin: `${CENTER}px ${CENTER}px` }}
            >
              {slices.map((slice) => {
                const { d, rounded } = slicePathFor(
                  slice.start,
                  slice.end,
                  slice.span,
                );
                if (!d) return null;
                const mid = (slice.start + slice.end) / 2;
                const out =
                  active === slice.id ? polar(0, 0, POP, mid) : { x: 0, y: 0 };
                return (
                  <path
                    key={slice.id}
                    d={d}
                    fill={slice.color}
                    stroke={rounded ? slice.color : undefined}
                    strokeWidth={rounded ? rounded * 2 : undefined}
                    strokeLinejoin="round"
                    className={styles.slice()}
                    style={{
                      transform: `translate(${out.x}px, ${out.y}px)`,
                      opacity:
                        active !== null && active !== slice.id ? 0.55 : 1,
                    }}
                    onPointerEnter={(event) => track(event, slice.id)}
                    onPointerMove={(event) => track(event, slice.id)}
                    onPointerLeave={leave}
                  />
                );
              })}
              {showLabels !== "none"
                ? slices.map((slice) => {
                    const room = isDonut
                      ? (RADIUS - inner) * 0.9
                      : RADIUS * 0.6;
                    const mid = (slice.start + slice.end) / 2;
                    const at = polar(
                      CENTER,
                      CENTER,
                      isDonut ? (RADIUS + inner) / 2 : RADIUS * 0.66,
                      mid,
                    );
                    const text =
                      showLabels === "percent"
                        ? `${percentFormatter.format(slice.share)}%`
                        : showLabels === "value"
                          ? valueFormatter(slice.amount)
                          : shorten(slice.label, 9);
                    // Only where the text fits inside the slice.
                    const arc =
                      ((slice.span * Math.PI) / 180) *
                      (isDonut ? (RADIUS + inner) / 2 : RADIUS * 0.66);
                    if (arc < text.length * 6.6 + 4 || room < 14) return null;
                    return (
                      <text
                        key={slice.id}
                        className={styles.sliceLabel()}
                        x={at.x}
                        y={at.y}
                        textAnchor="middle"
                        dominantBaseline="central"
                      >
                        {text}
                      </text>
                    );
                  })
                : null}
            </g>
            {isDonut && showTotal ? (
              <g className="pointer-events-none">
                <text
                  className={styles.centerValue()}
                  x={CENTER}
                  y={CENTER - 2}
                  textAnchor="middle"
                  fontSize={valueSize}
                >
                  {valueFormatter(current ? current.amount : total)}
                </text>
                <text
                  className={styles.centerLabel()}
                  x={CENTER}
                  y={CENTER + valueSize * 0.55 + 8}
                  textAnchor="middle"
                  fontSize={Math.max(10, valueSize * 0.4)}
                >
                  {current ? shorten(current.label, 16) : totalLabel}
                </text>
              </g>
            ) : null}
          </svg>
          {showTooltip && current && pointer ? (
            <div
              className={styles.tooltip()}
              style={{
                top: pointer.y,
                left: pointer.x,
                transform: `translate(${flip ? "calc(-100% - 12px)" : "12px"}, -50%)`,
              }}
            >
              <div className={styles.tooltipRow()}>
                <span
                  aria-hidden="true"
                  className={styles.swatch()}
                  style={{ background: current.color }}
                />
                <span className={styles.tooltipLabel()}>{current.label}</span>
                <span className={styles.tooltipValue()}>
                  {valueFormatter(current.amount)}
                </span>
              </div>
              <p className="m-0 mt-1 text-muted-fg">
                {percentFormatter.format(current.share)}% of the total
              </p>
            </div>
          ) : null}
        </div>
      ) : (
        <div className={styles.empty()} style={{ height: 140 }}>
          No data
        </div>
      )}

      {showLegend && hasData ? (
        <div className={styles.legend()}>
          {items
            .filter((item) => item.amount > 0)
            .map((item) => {
              const shown = !hidden.includes(item.id);
              return (
                <button
                  key={item.id}
                  type="button"
                  aria-pressed={shown}
                  onClick={() => toggle(item.id)}
                  onPointerEnter={() => shown && setActive(item.id)}
                  onPointerLeave={leave}
                  onFocus={() => shown && setActive(item.id)}
                  onBlur={leave}
                  className={styles.legendItem()}
                >
                  <span
                    aria-hidden="true"
                    className={cn(styles.swatch(), !shown && "opacity-40")}
                    style={{ background: item.color }}
                  />
                  {item.label}
                  <span className={styles.legendValue()}>
                    {valueFormatter(item.amount)}
                  </span>
                </button>
              );
            })}
        </div>
      ) : null}

      <table className="sr-only">
        <caption>{ariaLabel}</caption>
        <thead>
          <tr>
            <th scope="col">{index}</th>
            <th scope="col">{value}</th>
          </tr>
        </thead>
        <tbody>
          {items.map((item) => (
            <tr key={item.id}>
              <th scope="row">{item.label}</th>
              <td>{valueFormatter(item.amount)}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </figure>
  );
}

5. Use it

import { PieChart } from "@/components/ui/pie-chart/pie-chart";

Anatomy

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

<PieChart
  aria-label="Visitors by browser"
  data={[{ browser: "Chrome", visitors: 275 }, ...]}
  index="browser"
  value="visitors"
/>
PartRendered asNotes
Slicessvg pathOne per row, as wide as its share of the total. The one under the pointer moves out a little.
Centersvg textIn a donut, the total, or the number and name of the slice under the pointer.
Labelssvg textThe share, number or name on each slice big enough to hold it, with showLabels.
TooltipdivA card that follows the pointer with the name, number and share of the slice.
LegendbuttonOne button per row, with its number. Pressing it hides or shows the slice.
Data tabletable, sr-onlyThe same data as a table for screen readers. The SVG is hidden from them.

Examples

Usage

Point at a slice or at a name in the legend, and press a name to hide its slice.

Visitors by browser
browservisitors
Chrome275
Safari200
Firefox187
Edge173
Other90

Donut

variant donut cuts a hole in the middle. It holds the total, or the number and name of the slice under the pointer. totalLabel says what the total is.

Visitors by browser, as a donut
browservisitors
Chrome275
Safari200
Firefox187
Edge173
Other90

Labels on the slices

showLabels writes the share, the number or the name on each slice, and leaves out the ones too small to hold it.

percent

Visitors by browser, percent on the slices
browservisitors
Chrome275
Safari200
Firefox187
Edge173
Other90

value

Visitors by browser, value on the slices
browservisitors
Chrome275
Safari200
Firefox187
Edge173
Other90

name

Visitors by browser, name on the slices
browservisitors
Chrome275
Safari200
Firefox187
Edge173
Other90

Gaps and round corners

gap is the space between slices in degrees, and cornerRadius rounds their corners.

gap 0

Visitors, no gap
browservisitors
Chrome275
Safari200
Firefox187
Edge173
Other90

gap 6

Visitors, wide gap
browservisitors
Chrome275
Safari200
Firefox187
Edge173
Other90

cornerRadius 6

Visitors, rounded corners
browservisitors
Chrome275
Safari200
Firefox187
Edge173
Other90

Hole size

innerRadius is how big the hole of a donut is, as a share of the radius. A big hole makes a thin ring.

innerRadius 0.4

Visitors, inner radius 0.4
browservisitors
Chrome275
Safari200
Firefox187
Edge173
Other90

innerRadius 0.62

Visitors, inner radius 0.62
browservisitors
Chrome275
Safari200
Firefox187
Edge173
Other90

innerRadius 0.82

Visitors, inner radius 0.82
browservisitors
Chrome275
Safari200
Firefox187
Edge173
Other90

Order and start

sortOrder puts the biggest or the smallest first, and startAngle turns where the first slice starts, in degrees clockwise from the top.

Biggest first

Spending, biggest first
categoryamount
Food$640
Fun$210
Rent$1,200
Transport$280

Starting at 90°

Spending, starting at 90 degrees
categoryamount
Rent$1,200
Food$640
Transport$280
Fun$210

Legend

Put the legend below, above, or at either side of the chart, or turn it off.

Spending, with the legend on the right
categoryamount
Rent$1,200
Food$640
Transport$280
Fun$210

Colors

Slices take the chart colors of the theme in order. Give colors to choose them, any CSS colors or theme tokens, one for each row.

Test results
resultcount
Passed128
Skipped24
Failed9

Formatting values

valueFormatter writes the numbers, in the tooltip, the legend and the middle, and indexFormatter the names.

Spending by category
categoryamount
RENT$1,200
FOOD$640
TRANSPORT$280
FUN$210

One slice

A single row is a full circle.

All visitors from Chrome
browservisitors
Chrome275

No data

With no rows, or only zeros, it says so instead of drawing an empty circle.

No data
No visitors yet
browservisitors

Component API

PieChart takes the props below.

PropTypeDefault
dataRecord<string, unknown>[]-
indexstring-
valuestring-
aria-labelstring-
variant"pie" | "donut""pie"
innerRadiusnumber (0 to 0.9)0.62
colorsstring[]the theme's chart colors
sortOrder"none" | "descending" | "ascending""none"
startAnglenumber (degrees)0
gapnumber (degrees)1.5
cornerRadiusnumber0
showLabels"none" | "percent" | "value" | "name""none"
showTooltipbooleantrue
showLegendbooleantrue
legendPosition"top" | "bottom" | "left" | "right""bottom"
showTotalbooleantrue
totalLabelstring"Total"
valueFormatter(value: number) => stringnumber with grouping
indexFormatter(value: string) => stringthe value
sizenumber (px)260
classNamestring-