Skip to content

shadcn.io is an independent project built on shadcn/ui

Free

Pie chart

Parts of a whole, as a pie or a donut. Hovering pops a slice out and rolls the center to its value, and any slice takes a pattern or gradient.

On this page17 sections

Preview

Preview width

Installation

The command adds the example above to components/charts/ and, the first time, the chart kit to components/ui/charts/. Both are source files in your project from then on: read them, change them, delete what you don't use.

Sign in to get your install command
Free with an account. It carries your token, so the CLI installs everything in one go.

Usage

Each item has a label and a value. The slices take the theme's chart colors in order.

import { PieCenter, PieChart } from "@/components/ui/charts";

const data = [
  { label: "Starter", value: 18400 },
  { label: "Pro", value: 42600 },
  { label: "Business", value: 31200 },
];

export const PlanRevenueChart = () => (
  <PieChart ariaLabel="Revenue by plan" data={data} innerRadius={70} size={240}>
    <PieCenter defaultLabel="Revenue" prefix="$" />
  </PieChart>
);

Anatomy

The slices come from data. Children are optional: a PieSlice changes one slice, PieCenter fills a donut's hole.

<PieChart data={data} innerRadius={70}>
  <PieSlice index={0} showGlow />
  <PieCenter defaultLabel="Total" />
</PieChart>
  • PieChart: Draws one slice per item of data, in order.
  • PieSlice: Overrides one slice by index: its fill, hover effect or glow.
  • PieCenter: The total in a donut's hole, or the hovered slice's value.

Donut with a center

Any innerRadius above 0 turns the pie into a donut. Put a <PieCenter> inside and the hole shows the total, rolling to a slice's value on hover. prefix, suffix and formatOptions format the number.

Preview width

Hover effects

A hovered slice moves out by hoverOffset (10 px). On a <PieSlice>, hoverEffect="grow" extends it outward instead, and "none" keeps it still. showGlow adds a glow in the slice's color.

Preview width

With a legend

hoveredIndex and onHoverChange make the hover controlled. Share one index with a <ChartLegend> and hovering a slice highlights its row, and the other way round.

Preview width

Half donuts and spacing

startAngle and endAngle, in radians, set the sweep: -Math.PI / 2 to Math.PI / 2 is a half donut. padAngle spaces the slices and cornerRadius rounds them.

Preview width

Patterns and gradients

A slice's fill takes url(#id). Define a <PatternPreset> or a gradient inside the chart and point a slice at it, through its data item or a <PieSlice>.

Preview width

Customization

The kit is in your project, in components/ui/charts/: your framework's components over a shared core/. Change a default there and every chart picks it up.

className goes on the chart's container, so size and spacing are utility classes.

PieCenter renders the total and its label by default. Give it a function as its child to render your own: it gets value, label, isHovered and data, at rest with the total and on hover with the slice.

<PieCenter>
  {({ isHovered, label, value }) => (
    <div className="text-center">
      <div className="font-semibold text-2xl">{value.toLocaleString()}</div>
      <div className="text-muted-foreground text-xs">
        {isHovered ? label : "All plans"}
      </div>
    </div>
  )}
</PieCenter>

Where a part renders content of its own, you pass it in. In React:

  • PieCenter: {({ value, label, isHovered, data }) => …}

Loading state

The pie has no loading state of its own. Until the data arrives, render a round Skeleton at the chart's size, so nothing shifts when it mounts.

Animation

Slices sweep in one after another. enterTransition takes a motion-style transition (duration in seconds, an ease, or spring values), and enterStaggerScale stretches or shrinks the delay between slices: 0 starts them all at once.

animate={false} on a PieSlice draws that slice without the entrance. The center's number rolls to the hovered value. Reduced motion skips both.

Theming

Every color in the kit is one of your theme's tokens or a mix of them, except --chart-positive, a fixed green. A preset or the .dark class restyles the chart, and overriding a token in your CSS changes it everywhere.

Slices take --chart-1 to --chart-5 in order. Set color on a data item to pick one yourself. Past five slices the colors repeat, so give the extra slices their own.

TokenDefaultPaints
--chart-1your theme'sthe first series
--chart-2your theme'sthe second series
--chart-3your theme'sthe third series
--chart-4your theme'sthe fourth series
--chart-5your theme'sthe fifth series
--chart-label--muted-foregroundtick labels
globals.css
:root {
  --chart-label: var(--foreground);
}

Accessibility

The chart is an image named by ariaLabel ("Pie chart" by default). Name the total or the period in it, since the slices alone don't say what they add up to.

A slice focused from the keyboard reacts as it does on hover, and PieCenter shows its value.

Tab
Moves focus to the chart.
Arrow Right
Moves to the next slice. ArrowDown does the same.
Arrow Left
Moves to the previous slice. ArrowUp does the same.
Home
Jumps to the first slice.
End
Jumps to the last slice.

FAQ

When should I use a pie chart instead of a bar, waffle or ring chart?

Use a pie chart when a few categories add up to one total and the reader needs each one's rough share: a half, a quarter, a sliver. Keep it to about five slices, which is also where the theme's chart colors start to repeat.

Pick a bar chart to compare values precisely or to rank many categories, and a waffle chart when the shares are small and worth counting. A ring chart suits values that each have their own target, and a treemap or a sunburst chart suits parts that have parts of their own.

What data does the pie chart need?

An array with one item per slice, each with a label and a value. A slice's angle is its value's share of the sum, so pass the raw numbers and the chart works out the proportions.

Two optional fields paint a slice: color takes any CSS color or variable, and fill takes a url(#id) pattern or gradient and wins over color. Slices are drawn in the order of the array, clockwise from 9 o'clock, so sort the array yourself to rank them by size.

How do I make a donut chart with the total in the middle?

Set innerRadius on <PieChart>, in pixels: any value above 0 opens a hole. Add <PieCenter> as a child and the hole shows the sum of every value, with defaultLabel under it ("Total" unless you pass one).

While a slice is hovered or focused from the keyboard, the number rolls to that slice's value and the label becomes its name. Format the number with prefix, suffix and formatOptions, which takes Intl.NumberFormat options such as a currency or compact notation.

How do I show a slice's value or percentage on a pie chart?

The pie draws no tooltip and no labels on its slices. A donut reports the hovered slice in its hole instead: <PieCenter> shows that slice's value and label.

For a percentage, give <PieCenter> a function as its child. It's called with value, label and data, the total at rest and the slice on hover, so you can divide a slice's value by your own total.

A solid pie has no hole, and <PieCenter> renders nothing in it. Read the hovered index from onHoverChange and print the figure beside the chart or in a legend.

How do I add a legend to a pie chart?

Render a <ChartLegend> beside the chart and pass it your slices as items. Each item needs a label, a value and a color, so set color on the data items and both read the same array.

To link the two, keep the hovered index in state. Pass it to the chart as hoveredIndex with onHoverChange, and to the legend as hoveredIndex with onHover: hovering a slice then highlights its row, and hovering a row pops its slice out.

How do I make a half donut or semicircle pie chart?

Set the sweep with startAngle and endAngle, in radians measured clockwise from 12 o'clock. startAngle={-Math.PI / 2} with endAngle={Math.PI / 2} draws the top half, from 9 o'clock to 3 o'clock.

The chart's box stays square, so the lower half is empty space: pull the next element up with a negative margin in className. padAngle and cornerRadius space and round the slices.

If the half circle shows one reading against a range and not parts of a whole, use a gauge.

How do I change the slice colors or use patterns on a pie chart?

Slices take --chart-1 to --chart-5 in order and then repeat, so a sixth slice looks like the first. Set color on a data item to choose its color, with any CSS color or variable.

For a pattern or gradient, define a <PatternPreset> or a <RadialGradient> with an id inside the chart. Then point a slice at it with fill="url(#id)", on its data item or on a <PieSlice> with that slice's index.

How do I size a pie chart and make it responsive?

Pass size for a fixed width and height in pixels. Leave it out and the chart takes its parent's width and stays square, so the parent decides how large it gets.

innerRadius and hoverOffset are pixels and don't scale with the chart. The pie keeps hoverOffset (10 px) of padding around its edge so a hovered slice is never clipped, and on a narrow parent a fixed innerRadius leaves a thinner ring: choose it for the smallest width you support.

Which frameworks does the pie chart support?

React, Vue, Svelte and Solid. One core on TanStack Charts draws the pie chart in each, so the components and props on this page are the same everywhere, and switching framework at the top of the page changes the preview, the code and the install command.

Only the spelling follows the framework: class for className outside React, scoped slots for render props in Vue and snippets in Svelte.

How do I add the pie chart to my project?

Sign in, then copy the command under Installation: npx shadcn@latest add with the chart's URL. It adds the example at the top of this page as components/charts/chart-pie-default, the chart kit to components/ui/charts the first time you install a chart, and @tanstack/charts.

Both are source files in your project from then on. Swap the sample rows for your own data and change whatever you need.

Is the pie chart free?

Yes. The pie chart and every example of it are free to use in personal and commercial projects. Seeing the code and installing it takes a free account, one tap with Google or GitHub.

The charts are bklit's (bklit-ui, MIT), rebuilt on TanStack Charts and drawn in your shadcn/ui theme's tokens.

API reference

PieChart

PropType
dataPieData[]

The slices to draw, in order. Each item's value sets its share of the total, and its label is shown in the centre while the slice is hovered.

size?number

Chart width and height in pixels. Omit to fill the width of the parent element; the chart stays square.

innerRadius?number

Inner radius in pixels. 0 draws a solid pie; a positive value draws a donut and leaves room for PieCenter.

Default
0
padAngle?number

Gap between neighbouring slices, in radians.

Default
0
cornerRadius?number

Corner radius of each slice, in pixels.

Default
0
startAngle?number

Angle where the first slice starts, in radians, clockwise from 12 o'clock (d3's convention): the default -Math.PI / 2 is 9 o'clock. bklit-ui's own comment calls the default "top", but its d3 arcs start at 9 o'clock too.

Default
-Math.PI / 2
endAngle?number

Angle where the last slice ends, in radians. Together with startAngle this sets the sweep; the default is a full circle.

Default
(3 * Math.PI) / 2
className?string

Extra class name for the chart container.

style?CSSProperties

Inline styles for the chart container, merged over the default sizing.

hoveredIndex?number | null

Index of the hovered slice, for controlled hover. Pass null for no hover; leave it undefined to let the chart manage hover itself.

Type
number | null
onHoverChange?(index: number | null) => void

Called with the index of the hovered or keyboard-focused slice, or null when hover ends.

Type
(index: number | null) => void
hoverOffset?number

Distance in pixels a hovered slice moves out (or grows by). The pie also reserves this much padding around its edge so a hovered slice is never clipped. A PieSlice can override it for its own slice.

Default
10
childrenReactNode

PieSlice elements to configure individual slices, an optional PieCenter, and any pattern or gradient definitions that slices reference through fill.

enterTransition?PieEnterTransition

Transition for the slice entrance sweep, in the shape used by the motion library (type, duration in seconds, ease, and spring values). Defaults to a 1.1 second tween on the shared reveal curve.

enterStaggerScale?number

Multiplier for the delay between one slice's entrance and the next. 0 starts all slices together.

Default
1
geometryScrubbing?boolean

Turns off hover effects, PieSlice overrides and the hover readout in PieCenter. Meant for live editors that redraw the geometry while a control is dragged; leave it off otherwise.

Default
false
ariaLabel?string

Accessible name of the chart.

Default
"Pie chart"
ariaDescription?string

Longer accessible description of the chart.

PieSlice

PropType
indexnumber

Index of the slice this element configures, matching its position in the data array.

color?string

Colour of this slice's hover glow (showGlow). Defaults to the data item's color, then the palette. To paint the slice itself, set color on the PieData item, or use fill.

fill?string

Paint override for this slice, for example url(#patternId) for a pattern or gradient defined as a child of the chart. Takes precedence over the data item's color and fill.

animate?boolean

Play the entrance animation for this slice. Set false to draw it without animating.

Default
true
showGlow?boolean

Glow while the slice is hovered or keyboard-focused: a 12 px drop shadow in the slice's color.

Default
false
hoverEffect?PieSliceHoverEffect

How the slice reacts when hovered: "translate" moves it outward, "grow" extends its outer radius, "none" leaves it in place.

Default
"translate"
hoverOffset?number

Distance in pixels for the hover effect. Defaults to the chart's hoverOffset.

Default
the chart's `hoverOffset`

PieCenter

PropType
defaultLabel?string

Label shown under the total while no slice is hovered. A hovered slice shows its own label instead.

Default
"Total"
formatOptions?CenterStatFormat

Number format for the centre value, in Intl.NumberFormat terms (notation, currency, fraction digits and so on).

Default
{ maximumFractionDigits: 0, notation: "standard" }
children?(props: Readonly<PieCenterRenderProps>) => ReactNode

Render function for custom centre content, called with { value, label, isHovered, data } both at rest (the total, defaultLabel and isHovered: false) and while a slice is hovered (that slice). Branch on isHovered to style the two states.

Type
(props: Readonly<PieCenterRenderProps>) => ReactNode
className?string

Extra class name for the centre container.

valueClassName?string

Class name for the value text.

labelClassName?string

Class name for the label text.

prefix?string

Text shown before the value, for example "$".

suffix?string

Text shown after the value, for example "%".