# Using Charts

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

- Run-time users can save and re-open AG Grid charts they have created
- If Charting locations have been provided, they can choose where to display these charts

Run-time users of AdapTable can manage the charts which they create using AG Grid.

## Saving Charts

AdapTable users can name and save charts into [Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state/index.md).

This requires the `saveChartBehaviour` property in [Charting Options](https://www.adaptabletools.com/docs/technical-reference-charts/index.md) to be set to `manual` or `auto` (not `none`, the default)

With `manual`, a Notification prompts the user to provide a name for the Chart, whereupon the Chart is saved.

With `auto`, new charts are saved into State without that popup (AdapTable assigns naming behaviour as configured in the Charting flow).

## Opening Charts

Any AG Grid charts which have been named and saved will appear in a dropdown in:

- the Charting [Toolbar](https://www.adaptabletools.com/docs/ui-dashboard-tabs-toolbars/index.md) in the [Dashboard](https://www.adaptabletools.com/docs/ui-dashboard/index.md)
- the Charting [Tool Panel](https://www.adaptabletools.com/docs/ui-tool-panel/index.md)
- the Charting [Status Bar Panel](https://www.adaptabletools.com/docs/ui-status-bar/index.md)

Selecting a chart in any of these and clicking 'Open' will display the Chart.

- If specified Chart locations have been provided in [Charting Options](https://www.adaptabletools.com/docs/technical-reference-charts/index.md), users can select where to display the Chart
- See [Configuring Charts](https://www.adaptabletools.com/docs/handbook-charts-configuring/index.md) for more details on how to provide Chart locations

### Opening Saved Charts on Restart

By default, AdapTable does not store details of which Charts are currently opened in which Containers.

For many applications, use `restoreChartsOnReady` in [Charting Options](https://www.adaptabletools.com/docs/technical-reference-charts/index.md) to open persisted chart definitions when AdapTable loads — see [Configuring Charts](https://www.adaptabletools.com/docs/handbook-charts-configuring/index.md).

Alternatively, you can track open charts yourself using the [Chart Changed Event](https://www.adaptabletools.com/docs/technical-reference-charts/index.md) and the [Application section of Adaptable State](https://www.adaptabletools.com/docs/dev-guide-adaptable-state-custom/index.md).

The demo below uses Application State and Layouts to re-open charts when the application restarts or when the user switches layout

**Example: Displaying Saved Charts**

Display visible Charts when AdapTable restarts

- This example uses Application State to store details of which Charts were displayed
- Chart definitions (`bar`, `pie`) are registered in [Adaptable Ready](https://www.adaptabletools.com/docs/getting-started-adaptable-ready/index.md); Layout `OpenCharts` references those names
- Charts have been placed in 2 Layouts

- Switch between the 2 Layouts to see the Charts display in different Containers

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: 'Charts in App state',
  chartingOptions: {
    saveChartBehaviour: 'manual',
    chartContainers: [
      {
        name: 'Top Container',
        chartsDisplay: 'multiple',
        element: '#demoOutputAbove',
      },
      {
        name: 'Bottom Container',
        element: '#demoOutputBelow',
      },
    ],
  },
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Charting',
          Toolbars: ['Layout', 'Charting'],
        },
      ],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Charting'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Uuid: '22897acb-3ad1-4011-9fd0-0bf9f43d474e',
          Name: 'Standard Layout',
          TableColumns: [
            'github_stars',
            'github_watchers',
            'name',
            'language',
            'license',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'open_issues_count',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          AutoSizeColumns: true,
          OpenCharts: [
            {ChartName: 'bar', ContainerName: 'Top Container'},
            {ChartName: 'pie', ContainerName: 'Top Container'},
          ],
        },
        {
          Uuid: '04dff093-5388-4e9a-a320-6fd178e86260',
          Name: 'Demo Layout 2',
          TableColumns: [
            'github_stars',
            'github_watchers',
            'name',
            'language',
            'license',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'open_issues_count',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          AutoSizeColumns: true,
          OpenCharts: [
            {ChartName: 'pie', ContainerName: 'Bottom Container'},
          ],
        },
      ],
    },
  },
};
```

**`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,
  // enable charts and set a theme
  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, 'bar', {
    chartType: 'groupedBar',
    chartThemeName: 'ag-vivid-dark',
    cellRange: {
      rowStartIndex: 0,
      rowEndIndex: 7,
      columns: ['name', 'github_watchers'],
    },
  });

  registerRangeChartDefinition(adaptableApi, agGridApi, 'pie', {
    chartType: 'pie',
    chartThemeName: 'ag-vivid-dark',
    cellRange: {
      rowStartIndex: 0,
      rowEndIndex: 7,
      columns: ['name', 'github_watchers'],
    },
  });

  adaptableApi.layoutApi.setLayout('Standard Layout');
};
```

**`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,
#demoOutputBelow {
  display: flex;
  max-height: 500px;
}
```

## Closing Charts

Any open chart can be closed from the same locations which can open it.

## Editing Charts

Charts can be edited by clicking the _Edit_ button for that Chart in the [Charts Settings Panel](https://www.adaptabletools.com/docs/ui-settings-panel/index.md).

This will open the [Wizard](https://www.adaptabletools.com/docs/ui-settings-panel-wizards/index.md) for that Chart allowing it to be edited as required.

## Deleting Charts

Charts can be deleted by clicking the _Delete_ button for that Chart in the [Charts Settings Panel](https://www.adaptabletools.com/docs/ui-settings-panel/index.md).

### ReadOnly Charts

Individual Charts can be set to be read-only if required.

Read-only on a chart definition can restrict edit and delete actions in Charting UI independently of [Module Entitlements](https://www.adaptabletools.com/docs/handbook-permissioning-modules/index.md)

Read-Only Charts can be displayed and closed but they cannot be deleted or edited through the standard Charting UI.

There are 2 ways to set a Chart to Read-Only:

- Calling `setChartReadOnly` in [Charting API](https://www.adaptabletools.com/docs/technical-reference-charts/index.md) — including from [Adaptable Ready](https://www.adaptabletools.com/docs/getting-started-adaptable-ready/index.md) after registering the definition (see the demo below)
- Setting `IsReadOnly` to _true_ on the chart definition in [Charting Initial State](https://www.adaptabletools.com/docs/technical-reference-charts/index.md)

- To let end users mark a chart read-only during a session, expose `setChartReadOnly` from your own UI (for example a Custom Toolbar button)

**Example: Read-Only Charts**

Setting Charts to be Read-Only

- This example contains 2 Charts:
  - **Bar Chart** — can be displayed, edited, and deleted
  - **Pie Chart** — marked read-only via `setChartReadOnly` in [Adaptable Ready](https://www.adaptabletools.com/docs/getting-started-adaptable-ready/index.md); it can be displayed but not edited or deleted

- Switch between the 2 Charts and note how the Edit and Delete buttons in the Toolbar are alternately enabled / disabled

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: 'Read only Charts',
  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Charting',
          Toolbars: ['Charting'],
        },
      ],
    },
    StatusBar: {
      StatusBars: [
        {
          Key: 'Center Panel',
          StatusBarPanels: ['Charting'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Uuid: '22897acb-3ad1-4011-9fd0-0bf9f43d474e',
          Name: 'Standard Layout',
          TableColumns: [
            'github_stars',
            'github_watchers',
            'name',
            'language',
            'license',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'open_issues_count',
            'closed_issues_count',
            'open_pr_count',
            'closed_pr_count',
            'has_projects',
            'has_pages',
            'week_issue_change',
          ],
          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,
  // enable charts and set a theme
  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, 'Bar Chart', {
    chartType: 'groupedBar',
    chartThemeName: 'ag-vivid-dark',
    cellRange: {
      rowStartIndex: 0,
      rowEndIndex: 7,
      columns: ['name', 'github_watchers'],
    },
  });

  registerRangeChartDefinition(adaptableApi, agGridApi, 'Pie Chart', {
    chartType: 'pie',
    chartThemeName: 'ag-vivid-dark',
    cellRange: {
      rowStartIndex: 0,
      rowEndIndex: 7,
      columns: ['name', 'github_watchers'],
    },
  });

  const pieChart = adaptableApi.chartingApi.getChartDefinitionByName(
    'Pie Chart'
  );
  if (pieChart) {
    adaptableApi.chartingApi.setChartReadOnly(pieChart);
  }
};
```

**`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();
}
```
