# Pie chart

Share of a total across a small number of categories.

- Component: `<PieChart />`, imported from `em-kit`
- Required props: `dimension`, `measure` and `results`
- HTML page, with live previews: https://emkit.embeddable.com/docs/components/pie-chart
- Playground (needs a browser): https://emkit.embeddable.com/docs/components/pie-chart/playground

`PieChart` takes `dimension` + `measure`. Its siblings name their fields differently: `DonutLabelChart` takes `dimension` + `measure` + `innerLabelMeasure`.

## Install

```bash
npm install em-kit
pnpm add em-kit   # or, with pnpm
yarn add em-kit   # or, with yarn
bun add em-kit   # or, with bun
```

`react` and `react-dom` 19.1.1 or later are the only peer dependencies; Chart.js installs with the package. Wrap your app, or the part with charts, in `<ChartsProvider>` once: without it every chart throws `EmKit components must be rendered inside <ChartsProvider>.` Every example on this page includes `<ChartsProvider>` so that it runs on its own: if your app already has one, delete it from the example. A chart fills its parent, so the parent needs a height. In the Next.js App Router, every file that renders `ChartsProvider` or a chart starts with `'use client'`, and the provider pins the locale, `theme={{ formatter: { locale: 'en-US' } }}`, so the server and the browser format numbers alike. [The quick start](/docs/quick-start.md#in-the-nextjs-app-router) has the Next.js files.

## Usage

```tsx
import { ChartsProvider, PieChart, dimension, measure, results } from 'em-kit';

const industry = dimension({ name: 'industry', title: 'Industry' });
const revenue = measure({
  name: 'revenue',
  title: 'Revenue',
  inputs: { currency: 'USD', abbreviateLargeNumber: true },
});

export const Example = () => (
  <ChartsProvider>
    <div style={{ height: 440 }}>
      <PieChart
        title="Revenue by industry"
        dimension={industry}
        measure={revenue}
        results={results(rows)}
      />
    </div>
  </ChartsProvider>
);

const rows = [
  { industry: 'Health', revenue: 239005 },
  { industry: 'Media', revenue: 150918 },
  { industry: 'Retail', revenue: 180795 },
  { industry: 'Tech', revenue: 266759 },
];
```

## States

The chart draws its own states from `results`: a skeleton while `isLoading` is true and it has no rows, a spinner in the header while it reloads rows it already has, an empty state when `data` is `[]`, and the message when `error` is set. Pass your query’s state straight through.

## Examples

### Percentages

Each slice labelled with its share of the total. `showValueAsPercentage` on the measure works out the shares from your rows; no extra query. `decimalPlaces` rounds them.

```tsx
import { ChartsProvider, PieChart, dimension, measure, results } from 'em-kit';

const industry = dimension({ name: 'industry', title: 'Industry' });
const revenue = measure({
  name: 'revenue',
  title: 'Revenue',
  inputs: { currency: 'USD', decimalPlaces: 1, showValueAsPercentage: true },
});

export const Example = () => (
  <ChartsProvider>
    <div style={{ height: 440 }}>
      <PieChart
        title="Revenue by industry"
        dimension={industry}
        measure={revenue}
        results={results(rows)}
      />
    </div>
  </ChartsProvider>
);

const rows = [
  { industry: 'Health', revenue: 239005 },
  { industry: 'Media', revenue: 150918 },
  { industry: 'Retail', revenue: 180795 },
  { industry: 'Tech', revenue: 266759 },
];
```

### Long tail as “Other”

At most three slices: the first two rows, and the rest added up into one “Other” slice. `maxLegendItems` keeps your rows’ order, so sort the query largest first.

```tsx
import { ChartsProvider, PieChart, dimension, measure, results } from 'em-kit';

const industry = dimension({ name: 'industry', title: 'Industry' });
const revenue = measure({
  name: 'revenue',
  title: 'Revenue',
  inputs: { currency: 'USD', abbreviateLargeNumber: true },
});

export const Example = () => (
  <ChartsProvider>
    <div style={{ height: 440 }}>
      <PieChart
        title="Revenue by industry"
        dimension={industry}
        measure={revenue}
        results={results(rows)}
        maxLegendItems={3}
      />
    </div>
  </ChartsProvider>
);

const rows = [
  { industry: 'Tech', revenue: 266759 },
  { industry: 'Health', revenue: 239005 },
  { industry: 'Retail', revenue: 180795 },
  { industry: 'Media', revenue: 150918 },
];
```

## Props

Required props come first. A blank default means the prop is unset unless you pass it. Not listed: `showValueLabelsAsPercentage`, which the type accepts and the component does not read.

| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `dimension` | `Dimension` | yes |  | The field whose values label the axis or the segments. Its `name` is the row key. |
| `measure` | `Measure` | yes |  | The numeric field to plot. Its `inputs` (`prefix`, `suffix`, `decimalPlaces`) set the formatting. |
| `results` | `DataResponse` | yes |  | Your query’s state: `{ isLoading, data, error }`, where `data` is your rows. `results(rows)` builds it from an array. |
| `maxLegendItems` | `number` | no | `10` | Show at most this many segments. The rest are added up into one “Other” segment. |
| `showLegend` | `boolean` | no | `true` | Show the legend. Entries wrap onto more lines when they do not fit. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `onSegmentClick` | `(args: PieChartClickArg) => void` | no |  | Called with the clicked segment’s dimension value. Use it as a filter. A click on the “Other” segment reports the first of the rows it adds up, so ignore that one. |
| `componentName` | `string` | no |  | A name for this component, included in the interaction events it dispatches on the DOM, for your analytics. |
| `trackingId` | `string` | no |  | An id included in the same events, to tell two instances apart. |
| `title` | `string` | no |  | The card’s title. A `"key\|fallback"` string is looked up in your translations. |
| `description` | `string` | no |  | Smaller text under the title. Translates like `title`. |
| `tooltip` | `string` | no |  | Text for an info icon beside the title. |
| `hideMenu` | `boolean` | no | `false` | Hide the card’s header: the title, description and menu. |
| `menuOptions` | `("csv" \| "xlsx" \| "png" \| "maximize")[]` | no | `["csv", "xlsx", "png", "maximize"]` | Which entries the card menu offers. Pass `[]` for none. |

```ts
type PieChartClickArg = { dimensionValue: string | undefined; dimensionTimeRange: TimeRange; }
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```

Each is exported from `em-kit` as a type, for example `import type { PieChartClickArg } from 'em-kit'`.

A click payload’s `TimeRange` is `undefined` unless the clicked field is a time dimension, and its `relativeTimeString` is always `undefined`, so read it as `range?.from`. When you pass one, `from` and `to` are enough.

## Field options

Options go in a field’s `inputs`, for example `measure({ name: 'revenue', inputs: { prefix: '$' } })`. Every field takes `prefix`, `suffix`, `decimalPlaces`, `currency`, `abbreviateLargeNumber`, `displayName` and `maxCharacters`. [Field options](/docs/describing-your-data.md#field-options) describes them. `PieChart` also reads:

| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `showValueAsPercentage` | `boolean` | `measure` | `false` | Label each value with its share of the total. The tooltip shows both. |
