# Configuring Charts

Canonical page: https://www.adaptabletools.com/docs/handbook-charts-configuring

- AG Grid Charts can be defined and saved with AdapTable State
- Locations can be provided where AG Grid Charts can be displayed

## Defining Charts

AdapTable allows developers to [define](https://www.adaptabletools.com/docs/technical-reference-charts/index.md) Charts and save them in [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md).

Each [Chart Definition](https://www.adaptabletools.com/docs/technical-reference-charts/index.md) contains just 2 properties:

- `Name` - how the Chart appears in the AdapTable Charting UI
- `Model` - the AG Grid chart model returned by `getChartModels()`

### Providing Chart Definitions in Initial State

Use when definitions are stable and you accept maintaining the model across AG Grid upgrades — or seed State once from an exported model.

Provide a `Name` - this must be unique

`Model` must match the AG Grid version in use

```ts [[1, 2, "initialState"], [1, 3, "Charting"], [1, 4, "ChartDefinitions"], [2, 6, "Name"], [3, 7, "Model"]]
const adaptableOptions: AdaptableOptions = {
  initialState: {
    Charting: {
      ChartDefinitions: [
        {
          Name: 'Top Frameworks',
          Model: {
            /* AG Grid ChartModel — prefer registering via Charting API */
          },
        },
      ],
    },
  },
};
```

### Dynamic Definitions

AG Grid chart models frequently change between AG Grid / AG Charts versions.

This can result in a saved Chart Definition in Initial State getting out of date.

A good way to avoid this is to leverage the add / edit Chart Definitions functions in [Charting API](https://www.adaptabletools.com/docs/technical-reference-charts/index.md).

- Register definitions from a live chart (`createRangeChart` → `addChartDefinition`)
- The demos on this page seed chart definitions in [Adaptable Ready](https://www.adaptabletools.com/docs/getting-started-adaptable-ready/index.md) for that reason

### Registering Chart Definitions (recommended)

Use `agGridApi.createRangeChart` with `chartType`, `cellRange`, and optional theme.

Read the model from `agGridApi.getChartModels()`, then call `chartingApi.addChartDefinition`.

Destroy the temporary chart if it should not stay open.

```ts [[1, 5, "createRangeChart"], [2, 15, "getChartModels"], [2, 18, "addChartDefinition"], [2, 24, "destroyChart"]]
export const onAdaptableReady = ({
  adaptableApi,
  agGridApi,
}: AdaptableReadyInfo) => {
  const chartRef = agGridApi.createRangeChart({
    chartType: 'pie',
    chartThemeName: 'ag-vivid-dark',
    cellRange: {
      rowStartIndex: 0,
      rowEndIndex: 4,
      columns: ['name', 'github_stars'],
    },
  });
  const model = agGridApi
    .getChartModels()
    .find(m => m.chartId === chartRef?.chartId);
  if (model) {
    adaptableApi.chartingApi.addChartDefinition({
      Name: 'Top Frameworks',
      Model: model,
    });
  }
  if (chartRef) {
    chartRef.destroyChart();
  }
};
```

### Charts on Grouped Data

When the Layout has Row Grouping, a range Chart uses the Row Group Column as its category if either:

- the Row Group Column (`ag-Grid-AutoColumn`) is in the Chart's cell range (e.g. the user selected group cells when creating the Chart)
- `useGroupColumnAsCategory` is set to `true`

Otherwise the category is a column from the Chart's cell range (e.g. `model`).

`useGroupColumnAsCategory` is saved in the Chart's `Model`, so a Chart Definition keeps it when the Chart is reopened.

To always chart grouped rows by their group, set `useGroupColumnAsCategory: true` in `createRangeChart`, or in the `Model` of a Chart Definition in Initial State

```ts [[1, 7, "useGroupColumnAsCategory"]]
const chartRef = agGridApi.createRangeChart({
  chartType: 'groupedColumn',
  cellRange: {
    columns: ['model', 'price'],
  },
  // category is the Row Group Column whenever the Layout is grouped
  useGroupColumnAsCategory: true,
});
```

## Providing Chart Locations

AdapTable also allows developers to provide details of Chart Locations.

This is done through the `chartContainers` property of [Charting Options](https://www.adaptabletools.com/docs/technical-reference-charts/index.md).

Each location contains a Name and a reference to the `Div` element where Charts can be displayed.

### Understanding Chart Containers

The [`ChartContainer`](https://www.adaptabletools.com/docs/reference/chartcontainer.md) object is defined as follows:

| Property | Type | Description | Default |
| --- | --- | --- | --- |
| [chartsDisplay](https://www.adaptabletools.com/docs/reference/chartcontainer.md#chartsdisplay) | `'single' \| 'multiple'` | Whether 1 or more Charts can be displayed in same location | &#39;single&#39; |
| [element](https://www.adaptabletools.com/docs/reference/chartcontainer.md#element) | `HTMLElement \| string` | Location - can be HTMLElement or CSS Selector |   |
| [name](https://www.adaptabletools.com/docs/reference/chartcontainer.md#name) | `string` | Name of Container&#39;s Location - used in Dropdowns |   |

As can be seen it allows the following to be configured:

- **`name`** — label shown in Charting UI (toolbar, tool panel, layout `OpenCharts`)
- **`element`** — DOM node or CSS selector where the chart is drawn
- **`chartsDisplay`** — `'single'` (default) or `'multiple'` charts in that same container

The default Chart Container is the one provided by AG Grid and named 'AG Grid Window' by AdapTable

Use the `agGridContainerName` property in [Charting Options](https://www.adaptabletools.com/docs/technical-reference-charts/index.md) to provide a different name for this container

## Opening Charts Automatically

There are 2 main use cases where AdapTable might open a Chart automatically:

- when the application loads
- when a Layout is selected

### On Startup

Use this when you want saved chart definitions opened as soon as AdapTable is ready, without listing charts on the active Layout.

### `restoreChartsOnReady`

Open saved AG Grid charts when AdapTable loads

After AdapTable is ready, this option opens chart definitions that are already in [Charting State](https://www.adaptabletools.com/docs/technical-reference-charts/index.md).

Charts are opened in AG Grid's own chart window (the container labelled **AG Grid Window** by default, or the name from `agGridContainerName`).

This option does **not** pick a custom location from `chartContainers`.

To open charts in named containers on load, use **`OpenCharts`** on a Layout (below) or track visibility in the [Application section of Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-custom/index.md).

- If Current Layout defines `OpenCharts` (including empty array), AdapTable applies that on startup instead
- It **does not** use `restoreChartsOnReady`

Allowed values:

- **Omitted** or **`undefined`** (default) — no charts are opened automatically
- **`true`** or **`'all'`** — open every chart definition in State
- **`string[]`** — open only definitions whose **`Name`** matches an entry in the array; names that are not found are skipped

```ts {4}
// Open two named charts when the application loads
const adaptableOptions: AdaptableOptions = {
  chartingOptions: {
    restoreChartsOnReady: ['Top Frameworks', 'Issues & PRs'],
  },
};
```

### Per Layout

Add `OpenCharts` to a [Table Layout](https://www.adaptabletools.com/docs/handbook-layouts-table/index.md) or [Pivot Layout](https://www.adaptabletools.com/docs/handbook-layouts-pivot/index.md):

```ts
OpenCharts: [
  { ChartName: 'Top Frameworks', ContainerName: 'Above Grid' },
  { ChartName: 'Summary Chart' }, // optional — uses the AG Grid chart window
],
```

Chart names must be unique across all AG Grid and external chart definitions.

The chart wizard enforces this when saving or editing.

When the layout is selected, AdapTable closes other open AG Grid charts and opens the listed charts in the given containers.

Use an empty array (`OpenCharts: []`) to close all charts for that layout.

See [Using Charts](https://www.adaptabletools.com/docs/handbook-charts-using/index.md) for a demo that re-opens charts via Application State and Layouts

**Example: Chart Locations**

Showing AG Grid Charts in different locations

- This example demonstrates how to define Charts and Chart Locations
- 2 Charts are registered in [Adaptable Ready](https://www.adaptabletools.com/docs/getting-started-adaptable-ready/index.md) (`onAdaptableReady.ts` / `seedChartDefinitions.ts`):
  - `Top Frameworks` - a Pie Chart
  - `Issues & PRs` - a 100% stacked Bar Chart
- 2 Chart locations are provided in the `chartContainers` property of [Charting Options](https://www.adaptabletools.com/docs/technical-reference-charts/index.md):
  - `Above Grid` - appears above the Grid
  - `Below Grid` - appears below the Grid
- Additionally the `agGridContainerName` property has been set to 'Over Grid' - which overrides the default label of 'AG Grid Window'

- Open _Top Frameworks_ in the `Above Grid` chart location
- Open _Issues & PRs_ in the `Below Grid` chart location

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts         [template, with charts]
  columnDefs.ts            [template]
  gridOptions.ts
  index.ts                 [template]
  onAdaptableReady.ts
  rowData.ts               [template]
  seedChartDefinitions.ts
  styles.css               [template]
index.html                 [template]
package.json               [template] + ag-charts-enterprise
tsconfig.json              [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Chart Locations',
  chartingOptions: {
    chartContainers: [
      {
        name: 'Above Grid',
        element: '#demoOutputAbove',
      },
      {
        name: 'Below Grid',
        element: '#demoOutputBelow',
      },
    ],
    agGridContainerName: 'Over Grid',
  },
  initialState: {
    Dashboard: {
      Tabs: [{Name: 'Charting', Toolbars: ['Charting']}],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Charting'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'github_stars',
            'name',
            'open_issues_count',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'github_watchers',
            'language',
            'license',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          ColumnSorts: [{ColumnId: 'github_stars', SortOrder: 'Desc'}],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {rowData} from './rowData';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,

    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  enableCharts: true,
  chartThemes: ['ag-vivid', 'ag-vivid-dark'],
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';
import {registerRangeChartDefinition} from './seedChartDefinitions';

export const onAdaptableReady = ({
  adaptableApi,
  agGridApi,
}: AdaptableReadyInfo) => {
  registerRangeChartDefinition(adaptableApi, agGridApi, 'Top Frameworks', {
    chartType: 'pie',
    chartThemeName: 'ag-vivid-dark',
    cellRange: {
      rowStartIndex: 0,
      rowEndIndex: 4,
      columns: ['name', 'github_stars'],
    },
  });

  registerRangeChartDefinition(adaptableApi, agGridApi, 'Issues & PRs', {
    chartType: 'normalizedBar',
    chartThemeName: 'ag-vivid-dark',
    cellRange: {
      rowStartIndex: 0,
      rowEndIndex: 9,
      columns: [
        'name',
        'open_issues_count',
        'closed_issues_count',
        'open_pr_count',
        'closed_pr_count',
      ],
    },
  });
};
```

**`src/seedChartDefinitions.ts`**

```ts
import type {AdaptableApi} from '@adaptabletools/adaptable';
import type {CreateRangeChartParams, GridApi} from 'ag-grid-enterprise';

/**
 * Registers a named AdapTable Chart Definition using AG Grid's live chart model.
 * Prefer this over hand-written `ChartModel` JSON in Initial State — AG Grid chart
 * models change between AG Grid / AG Charts versions.
 */
export function registerRangeChartDefinition(
  adaptableApi: AdaptableApi,
  agGridApi: GridApi,
  name: string,
  params: CreateRangeChartParams
): void {
  const chartRef = agGridApi.createRangeChart(params);
  if (!chartRef?.chartId) {
    return;
  }
  const models = agGridApi.getChartModels();
  const model = models?.find(m => m.chartId === chartRef.chartId);
  if (model) {
    adaptableApi.chartingApi.addChartDefinition({Name: name, Model: model});
  }
  chartRef.destroyChart();
}
```

## Multiple Charts in a Location

By default AdapTable will display one chart in each provided Location.

This means that loading a new chart will displace any currently displayed Chart.

This behaviour can be changed by setting `chartsDisplay` to `'multiple'` on a [`ChartContainer`](https://www.adaptabletools.com/docs/reference/chartcontainer.md) in `chartContainers`.

When `chartsDisplay` is `'multiple'`, charts are **appended** to that container's `element`.

- To place multiple charts in a container, it needs a fixed height - e.g. `max-height` or `display: flex`
- Without this the charts will grow inside the Div infinitely

**Example: Multiple Charts in Location**

Showing multiple AG Grid Charts in a Div

- This example demonstrates how to show multiple charts in the same location:
  - The **Above Grid** chart container has `chartsDisplay: 'multiple'` (see `adaptableOptions.ts` and `onAdaptableReady.ts` in the demo tabs)
  - Two chart definitions are registered in [Adaptable Ready](https://www.adaptabletools.com/docs/getting-started-adaptable-ready/index.md)
  - The container uses `display: flex` in CSS so multiple charts can share the div
  - In the [Adaptable Ready Event](https://www.adaptabletools.com/docs/getting-started-adaptable-ready/index.md), [Charting API](https://www.adaptabletools.com/docs/technical-reference-charts/index.md) methods open both charts in that container

- Use the Charting toolbar to open each chart in **Above Grid** and confirm both can remain visible

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts         [template, with charts]
  columnDefs.ts            [template]
  gridOptions.ts
  index.ts                 [template]
  onAdaptableReady.ts
  rowData.ts               [template]
  seedChartDefinitions.ts
  styles.css               [template + shown below]
index.html                 [template]
package.json               [template] + ag-charts-enterprise
tsconfig.json              [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Multiple Charts',
  chartingOptions: {
    chartContainers: [
      {
        name: 'Above Grid',
        element: '#demoOutputAbove',
        chartsDisplay: 'multiple',
      },
    ],
  },
  initialState: {
    Dashboard: {
      Tabs: [{Name: 'Charting', Toolbars: ['Charting']}],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Charting'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'github_stars',
            'name',
            'open_issues_count',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'github_watchers',
            'language',
            'license',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          ColumnSorts: [{ColumnId: 'github_stars', SortOrder: 'Desc'}],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {rowData} from './rowData';
import {columnDefs} from './columnDefs';

export const gridOptions: GridOptions = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,

    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  enableCharts: true,
  chartThemes: ['ag-vivid', 'ag-vivid-dark'],
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```

**`src/onAdaptableReady.ts`**

```ts
import {AdaptableReadyInfo} from '@adaptabletools/adaptable';
import {registerRangeChartDefinition} from './seedChartDefinitions';

export const onAdaptableReady = ({
  adaptableApi,
  agGridApi,
}: AdaptableReadyInfo) => {
  registerRangeChartDefinition(adaptableApi, agGridApi, 'Top Frameworks', {
    chartType: 'pie',
    chartThemeName: 'ag-vivid-dark',
    cellRange: {
      rowStartIndex: 0,
      rowEndIndex: 4,
      columns: ['name', 'github_stars'],
    },
  });

  registerRangeChartDefinition(adaptableApi, agGridApi, 'Issues & PRs', {
    chartType: 'normalizedBar',
    chartThemeName: 'ag-vivid-dark',
    cellRange: {
      rowStartIndex: 0,
      rowEndIndex: 9,
      columns: [
        'name',
        'open_issues_count',
        'closed_issues_count',
        'open_pr_count',
        'closed_pr_count',
      ],
    },
  });

  const topChartContainer = document.getElementById(
    'demoOutputAbove'
  ) as HTMLDivElement;
  const chartDefs = adaptableApi.chartingApi.getChartDefinitions();
  adaptableApi.chartingApi.showChartDefinition(chartDefs[0], topChartContainer);
  adaptableApi.chartingApi.showChartDefinition(chartDefs[1], topChartContainer);
};
```

**`src/seedChartDefinitions.ts`**

```ts
import type {AdaptableApi} from '@adaptabletools/adaptable';
import type {CreateRangeChartParams, GridApi} from 'ag-grid-enterprise';

/**
 * Registers a named AdapTable Chart Definition using AG Grid's live chart model.
 * Prefer this over hand-written `ChartModel` JSON in Initial State — AG Grid chart
 * models change between AG Grid / AG Charts versions.
 */
export function registerRangeChartDefinition(
  adaptableApi: AdaptableApi,
  agGridApi: GridApi,
  name: string,
  params: CreateRangeChartParams
): void {
  const chartRef = agGridApi.createRangeChart(params);
  if (!chartRef?.chartId) {
    return;
  }
  const models = agGridApi.getChartModels();
  const model = models?.find(m => m.chartId === chartRef.chartId);
  if (model) {
    adaptableApi.chartingApi.addChartDefinition({Name: name, Model: model});
  }
  chartRef.destroyChart();
}
```

**`src/styles.css`**

```css
#demoOutputAbove {
  display: flex;
}
```

### `agGridContainerName`

Name of AG Grid Chart Container

Multiple containers can be provided for charts at design-time.

When this happens the container provided by AG Grid (which appears in the middle of the screen) is added to the list.

By default this container is entitled "AG Grid Window", but this property allows this container to be renamed.

```ts {4}
// Rename the AG Grid container to "Grid"
const adaptableOptions: AdaptableOptions = {
  chartingOptions: {
    agGridContainerName: 'Grid',
  },
};
```

### `chartContainers`

Locations to display saved Charts

  [`ChartContainer[]`](https://www.adaptabletools.com/docs/reference/chartcontainer.md)

Defines locations where AG Grid charts which have been saved into [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md) can be displayed.

These locations, if provided, appear in a dropdown in the Charting [Toolbar](https://www.adaptabletools.com/docs/ui-dashboard-tabs-toolbars/index.md) and [Tool Panel](https://www.adaptabletools.com/docs/ui-tool-panel/index.md).

This **doesn't** override the `createChartContainer` property in AG Grid's GridOptions

The [`ChartContainer`](https://www.adaptabletools.com/docs/reference/chartcontainer.md) object is defined as follows:

| Property | Type | Description | Default |
| --- | --- | --- | --- |
| [chartsDisplay](https://www.adaptabletools.com/docs/reference/chartcontainer.md#chartsdisplay) | `'single' \| 'multiple'` | Whether 1 or more Charts can be displayed in same location | &#39;single&#39; |
| [element](https://www.adaptabletools.com/docs/reference/chartcontainer.md#element) | `HTMLElement \| string` | Location - can be HTMLElement or CSS Selector |   |
| [name](https://www.adaptabletools.com/docs/reference/chartcontainer.md#name) | `string` | Name of Container&#39;s Location - used in Dropdowns |   |

Assuming you created your page like this:

```html
<div id="top-chart-container"></div>
<div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
  <div id="adaptable" style={{ margin: 0 }} />
  <div id="grid"  style={{ flex: 1 }}></div>
</div>
<div id="chart-container-bottom"></div>
```

You could define Chart Containers as follows:

```ts {9}
// Get the HTML Element for chart-container
const topChartContainer = document.getElementById(
  'top-chart-container'
) as HTMLDivElement;

// Supply 2 Containers:
// 1. Placed above Grid and defined as an HTML Element, allowing multiple Charts
// 2. Placed below the Grid and referenced by name
const adaptableOptions: AdaptableOptions = {
  chartingOptions: {
    chartContainers: [
      {
        name: 'Above Grid',
        element: topChartContainer,
        chartsDisplay: 'multiple',
      },
      {
        name: 'Below Grid',
        element: '#chart-container-bottom',
      },
    ],
  },
};
```

### `saveChartBehaviour`

Behaviour for saving Charts into AdapTable State

By default AdapTable will not save any AG Grid charts the user creates into AdapTable State.

This property offers 3 options:

- `auto`: all created charts are saved automatically in Adaptable state
- `manual`: a popup is shown to the user to save the chart
- `none`: charts are not saved

```ts {4}
// Tell AdapTable to display a popup each time a new Chart is created
const adaptableOptions: AdaptableOptions = {
  chartingOptions: {
    saveChartBehaviour: 'manual',
  },
};
```
