# Bar and line combo

Bars and a line on independent axes, for volume against a rate or count.

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

`BarLineChart` takes `dimension` + `measures`. Its siblings name their fields differently: `BarChartStacked` and `BarChartGrouped` take `xAxis` + `groupBy` + `measure`; `BarChartStackedHorizontal` and `BarChartGroupedHorizontal` take `yAxis` + `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,
  BarLineChart,
  dimension,
  measure,
  results,
} from 'em-kit';

const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({
  name: 'customers',
  title: 'Customers',
  inputs: { abbreviateLargeNumber: true },
});
const churnRate = measure({
  name: 'churn_rate',
  title: 'Churn rate',
  inputs: { suffix: '%', decimalPlaces: 1, useSecondaryAxis: true },
});

export const Example = () => (
  <ChartsProvider>
    <div style={{ height: 360 }}>
      <BarLineChart
        title="Customers and churn rate by plan"
        dimension={plan}
        measures={[customers]}
        lineMeasures={[churnRate]}
        results={results(rows)}
        showValueLabels={false}
      />
    </div>
  </ChartsProvider>
);

const rows = [
  { plan: 'Starter', customers: 1283, churn_rate: 4.8 },
  { plan: 'Growth', customers: 1085, churn_rate: 2.7 },
  { plan: 'Enterprise', customers: 207, churn_rate: 1.1 },
];
```

- `useSecondaryAxis` on a line measure gives the line its own scale, on the right.
- `showValueLabels` labels the bars and `showValueLabelsLine` the line, both on by default. Here the bars are plain, so the line never runs through a bar’s label.

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

### Axis titles

A caption on each value axis, so it’s clear which scale belongs to which series.

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

const plan = dimension({ name: 'plan', title: 'Plan' });
const customers = measure({
  name: 'customers',
  title: 'Customers',
  inputs: { abbreviateLargeNumber: true },
});
const churnRate = measure({
  name: 'churn_rate',
  title: 'Churn rate',
  inputs: { suffix: '%', decimalPlaces: 1, useSecondaryAxis: true },
});

export const Example = () => (
  <ChartsProvider>
    <div style={{ height: 360 }}>
      <BarLineChart
        title="Customers and churn rate by plan"
        dimension={plan}
        measures={[customers]}
        lineMeasures={[churnRate]}
        results={results(rows)}
        showValueLabels={false}
        yAxisLabel="Customers"
        yAxisSecondaryLabel="Churn rate"
        yAxisSecondaryMin={0}
      />
    </div>
  </ChartsProvider>
);

const rows = [
  { plan: 'Starter', customers: 1283, churn_rate: 4.8 },
  { plan: 'Growth', customers: 1085, churn_rate: 2.7 },
  { plan: 'Enterprise', customers: 207, churn_rate: 1.1 },
];
```

## Props

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

| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
| `dimension` | `Dimension` | yes |  | The field whose values label the axis or the segments. Its `name` is the row key. |
| `measures` | `Measure[]` | yes |  | The numeric fields to plot, one series each. Their `inputs` 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. |
| `lineMeasures` | `Measure[]` | no |  | Measures drawn as lines over the bars. Set `useSecondaryAxis` on a measure to give it the right-hand axis. |
| `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. |
| `showValueLabels` | `boolean` | no | `true` | Print each value on the chart. |
| `showValueLabelsLine` | `boolean` | no | `true` | Print the line’s values too. |
| `xAxisLabel` | `string` | no |  | A title under the x-axis. |
| `yAxisLabel` | `string` | no |  | A title beside the y-axis. |
| `yAxisRangeMin` | `number` | no |  | Fix the lowest value on the y-axis. When unset, a bar, line or area chart’s axis includes zero, and a scatter or bubble chart’s fits the data. |
| `yAxisRangeMax` | `number` | no |  | Fix the highest value on the y-axis. When unset, it fits the data. |
| `reverseXAxis` | `boolean` | no | `false` | Reverse the order of the x-axis. |
| `xAxisMaxItems` | `number` | no |  | Show at most this many x values. The rest are added up into one “Other” value. |
| `yAxisSecondaryLabel` | `string` | no |  | A title beside the right-hand axis. |
| `yAxisSecondaryMin` | `number` | no |  | Fix the lowest value on the right-hand axis. |
| `yAxisSecondaryMax` | `number` | no |  | Fix the highest value on the right-hand 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: BarLineChartClickArg) => void` | no |  | Called with the clicked bar’s dimension value and, on a time axis, its date range. Use it as a filter. |
| `onLineClicked` | `(args: BarLineChartClickArg) => void` | no |  | Called with the clicked point’s dimension value and date range. |
| `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 BarLineChartClickArg = { dimensionValue: string | undefined; dimensionTimeRange: 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 { BarLineChartClickArg } 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 `dimension` 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. `BarLineChart` also reads:

| Option | Type | Set on | Default | Description |
|---|---|---|---|---|
| `color` | `string` | `measures` |  | A colour for this measure’s bars, in place of the theme’s. |
| `showValueAsPercentage` | `boolean` | `measures` | `false` | Label each value with its share of the total. The tooltip shows both. |
| `lineColor` | `string` | `lineMeasures` |  | A colour for this measure’s line, in place of the theme’s. |
| `dashedLine` | `boolean` | `lineMeasures` | `false` | Draw the line dashed. |
| `connectGaps` | `boolean` | `lineMeasures` | `false` | Draw a missing value as zero, so the line carries on. When off, the line breaks at the gap. |
| `fillUnderLine` | `boolean` | `lineMeasures` |  | Shade the area under the line. |
| `useSecondaryAxis` | `boolean` | `lineMeasures` |  | Plot this measure against the right-hand axis, with its own scale. |
