# Grouped horizontal bar chart

Side-by-side bars for each value of a second dimension, laid out horizontally.

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

`BarChartGroupedHorizontal` takes `yAxis` + `groupBy` + `measure`. Its siblings name their fields differently: `BarChart`, `BarChartHorizontal` and `BarLineChart` take `dimension` + `measures`; `BarChartStacked` and `BarChartGrouped` take `xAxis` + `groupBy` + `measure`.

## 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,
  BarChartGroupedHorizontal,
  dimension,
  measure,
  results,
} from 'em-kit';

const plan = dimension({ name: 'plan', title: 'Plan' });
const billing = dimension({ name: 'billing', title: 'Billing' });
const customers = measure({
  name: 'customers',
  title: 'Customers',
  inputs: { abbreviateLargeNumber: true },
});

export const Example = () => (
  <ChartsProvider>
    <div style={{ height: 360 }}>
      <BarChartGroupedHorizontal
        title="Customers by plan and billing"
        yAxis={plan}
        groupBy={billing}
        measure={customers}
        results={results(rows)}
      />
    </div>
  </ChartsProvider>
);

const rows = [
  { plan: 'Starter', billing: 'Monthly', customers: 1052 },
  { plan: 'Starter', billing: 'Annual', customers: 231 },
  { plan: 'Growth', billing: 'Monthly', customers: 586 },
  { plan: 'Growth', billing: 'Annual', customers: 499 },
  { plan: 'Enterprise', billing: 'Monthly', customers: 25 },
  { plan: 'Enterprise', billing: 'Annual', customers: 182 },
];
```

- The `yAxis` values are drawn A to Z, whatever the order of your rows, unless you pass `axisOrder`.

## 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

### Value labels

Every bar labelled with its value.

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

const plan = dimension({ name: 'plan', title: 'Plan' });
const billing = dimension({ name: 'billing', title: 'Billing' });
const customers = measure({
  name: 'customers',
  title: 'Customers',
  inputs: { abbreviateLargeNumber: true },
});

export const Example = () => (
  <ChartsProvider>
    <div style={{ height: 360 }}>
      <BarChartGroupedHorizontal
        title="Customers by plan and billing"
        yAxis={plan}
        groupBy={billing}
        measure={customers}
        results={results(rows)}
        showValueLabels
      />
    </div>
  </ChartsProvider>
);

const rows = [
  { plan: 'Starter', billing: 'Monthly', customers: 1052 },
  { plan: 'Starter', billing: 'Annual', customers: 231 },
  { plan: 'Growth', billing: 'Monthly', customers: 586 },
  { plan: 'Growth', billing: 'Annual', customers: 499 },
  { plan: 'Enterprise', billing: 'Monthly', customers: 25 },
  { plan: 'Enterprise', billing: 'Annual', customers: 182 },
];
```

## Props

Required props come first. A blank default means the prop is unset unless you pass it.

| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `yAxis` | `Dimension` | yes |  | The dimension down the y-axis of a horizontal chart. |
| `groupBy` | `Dimension` | yes |  | A second dimension that splits each axis value into one series per value. |
| `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. |
| `resultsAxisOrder` | `DataResponse` | no |  | A separate result listing the axis values in the order to draw them, for example largest first. Reported back through `setAxisOrderAndCacheKey`. |
| `axisOrder` | `string[]` | no |  | The axis values in the order to draw them. Values missing from the list are left out. |
| `axisOrderCacheKey` | `string` | no |  | Any string identifying the `resultsAxisOrder` query. Passed back as the second argument of `setAxisOrderAndCacheKey`, which is only called when this is set. |
| `setAxisOrderAndCacheKey` | `(values: string[], cacheKey: string) => void` | no |  | Called with the values from `resultsAxisOrder` and `axisOrderCacheKey` once that result has loaded. Store the values and pass them as `axisOrder`. |
| `resultsGroupOrder` | `DataResponse` | no |  | A separate result listing the `groupBy` values in the order you want, for example largest first. Reported back through `setGroupOrderAndCacheKey`. |
| `resultsGroupOther` | `DataResponse` | no |  | Totals per axis value across every group. The chart subtracts the groups in `results` and draws what is left as an “Other” series. |
| `groupOrderCacheKey` | `string` | no |  | Any string identifying the `resultsGroupOrder` query. Passed back as the second argument of `setGroupOrderAndCacheKey`, which is only called when this is set. |
| `setGroupOrderAndCacheKey` | `(values: string[], cacheKey: string) => void` | no |  | Called with the values from `resultsGroupOrder` and `groupOrderCacheKey` once that result has loaded. Store them to query only the top groups. |
| `showLegend` | `boolean` | no | `true` | Show the legend. A chart with one series shows none; entries wrap onto more lines when they do not fit. |
| `showLogarithmicScale` | `boolean` | no | `false` | Use a logarithmic value axis, for values that span several orders of magnitude. |
| `showTooltips` | `boolean` | no | `true` | Show a formatted tooltip on hover. |
| `showTotalLabels` | `boolean` | no | `false` | Print the total at the end of each stack. |
| `showValueLabels` | `boolean` | no | `false` | Print each value on the chart. |
| `xAxisLabel` | `string` | no |  | A title under the x-axis. |
| `yAxisLabel` | `string` | no |  | A title beside the y-axis. |
| `granularity` | `Granularity` | no |  | Only sets the size of the date range a click reports (`dimensionTimeRange`). The axis labels and the gap filling come from the time field, `dimension({ granularity })`, and this prop follows the field when left out. One of `"second"`, `"minute"`, `"hour"`, `"day"`, `"week"`, `"month"`, `"quarter"`, `"year"`. |
| `setGranularity` | `(granularity: Granularity) => void` | no |  | Called with the granularity the reader picks in the card. The picker only shows when the time field sets `showGranularityDropdown: true` in its `inputs`. Store the value, set it as the field’s `granularity` and pass rows at that granularity. |
| `onBarClicked` | `(args: BarChartStackedOptionsClickArg) => void` | no |  | Called with the clicked bar’s dimension value and, on a time axis, its date range. Use it as a filter. |
| `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. |
| `reverseYAxis` | `boolean` | no | `false` | Reverse the order of the y-axis. |
| `xAxisRangeMax` | `number` | no |  | Fix the highest value on the x-axis. When unset, it fits the data. |
| `xAxisRangeMin` | `number` | no |  | Fix the lowest value on the x-axis. When unset, a horizontal bar chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |

```ts
type BarChartStackedOptionsClickArg = { dimensionValue: string | number | undefined; dimensionTimeRange: TimeRange; measureValues?: Record<string, unknown> | undefined; groupingDimensionValue: string | undefined; groupingDimensionTimeRange: TimeRange; }
type Granularity = "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
type TimeRange = { from: Date | undefined; to: Date | undefined; relativeTimeString?: string; } | undefined
```

Each is exported from `em-kit` as a type, for example `import type { BarChartStackedOptionsClickArg } 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`. A time dimension in `yAxis` also takes `granularity`, `showGranularityDropdown`, `dateBounds` and `ignoreEmptyDate`. Its `granularity` is what labels the axis as dates and fills periods with no row; `dimension()` takes it in `inputs` or at the top level, `dimension({ granularity: 'month' })`. [Field options](/docs/describing-your-data.md#field-options) describes them.
