Learn about creating and updating charts in more detail.
Creating and Updating Charts Copy Link
AgCharts exposes a static create() method to perform chart initialisation, and the resulting AgChartInstance has methods such as AgChartInstance.update() to allow updating configuration.
The AgChartOptions type defines the configuration structure. See the Options Reference for more details.
Mutations to the previously used options object are not automatically picked up by the chart implementation. AgChartInstance.update() or AgChartInstance.updateDelta() should be called to apply changes.
We expect the options supplied to AgChartInstance.update() to be the full configuration state for the chart, not a partial configuration. Use AgChartInstance.updateDelta() to apply partial updates.
We expect immutable data for data elements and theme options, as this enables efficient change detection. If data elements or theme options are mutated in-place, we cannot guarantee to detect the changes.
- create
Function - Create a new `AgChartInstance` based upon the given configuration options.
- createFinancialChart
Function - Create a new `AgChartInstance` based upon the given configuration options.
- createGauge
Function - Create a new `AgChartInstance` based upon the given configuration options.
- createQuadrantChart
Function - Create a new `AgChartInstance` based upon the given configuration options.
- create
Function - Create a new `AgChartInstance` based upon the given configuration options.
- createFinancialChart
Function - Create a new `AgChartInstance` based upon the given configuration options.
- createGauge
Function - Create a new `AgChartInstance` based upon the given configuration options.
- createQuadrantChart
Function - Create a new `AgChartInstance` based upon the given configuration options.
- update
Function - Update an existing `AgChartInstance`. Options provided should be complete and not partial. Returns a `Promise` that resolves once the requested change has been rendered. __Note:__ As each call could trigger a chart redraw, multiple calls in quick succession could result in undesirable flickering. Callers should batch up and/or debounce changes to avoid unintended partial update renderings.
- updateDelta
Function - Update an existing `AgChartInstance` by applying a partial set of option changes. Returns a `Promise` that resolves once the requested change has been rendered. __Note:__ As each call could trigger a chart redraw, each individual delta options update should leave the chart in a valid options state. Also, multiple calls in quick succession could result in undesirable flickering. Callers should batch up and/or debounce changes to avoid unintended partial update renderings.
- getOptions
Function - Get the `AgChartOptions` representing the current chart configuration.
- applyTransaction
Function - Apply a transaction to incrementally update the chart data without replacing the entire dataset. Returns a `Promise` that resolves once the transaction has been applied and rendered
- waitForUpdate
Function - Returns a `Promise` that resolves once any pending changes have been rendered.
- download
Function - Starts a browser-based image download for the given `AgChartInstance`. Returns a `Promise` that resolves once the download has been initiated.
- getImageDataURL
Function - Returns a base64-encoded image data URL for the given `AgChartInstance`.
- getState
Function - Returns a representation of the current state of the given `AgChartInstance`.
- setState
Function - Sets the state of the given `AgChartInstance` to the state provided.
- getSelection
Function - Retrieve the current selection. An error may be thrown if the chart state mutates whilst the selection items are being iterated. Returns An iterable of all selected items.
- setSelection
Function - Replaces the current selection.
- clearSelection
Function - Clear the entire selection state of all items on all series.
- isModuleRegistered
Function - Returns whether a module is available to this chart, either registered globally or passed to it via `AgCharts.create(options, { modules })`. Param moduleId the exported name of a module, such as `'LineSeriesModule'`. Bundles such as `AllCommunityModule` are not modules; `'QuadrantChartModule'` is accepted because the quadrant preset is only exported as a bundle.
- destroy
Function - Destroy the chart instance and any allocated resources supporting its rendering.
- update
Function - Update an existing `AgChartInstance`. Options provided should be complete and not partial. Returns a `Promise` that resolves once the requested change has been rendered. __Note:__ As each call could trigger a chart redraw, multiple calls in quick succession could result in undesirable flickering. Callers should batch up and/or debounce changes to avoid unintended partial update renderings.
- updateDelta
Function - Update an existing `AgChartInstance` by applying a partial set of option changes. Returns a `Promise` that resolves once the requested change has been rendered. __Note:__ As each call could trigger a chart redraw, each individual delta options update should leave the chart in a valid options state. Also, multiple calls in quick succession could result in undesirable flickering. Callers should batch up and/or debounce changes to avoid unintended partial update renderings.
- getOptions
Function - Get the `AgChartOptions` representing the current chart configuration.
- applyTransaction
Function - Apply a transaction to incrementally update the chart data without replacing the entire dataset. Returns a `Promise` that resolves once the transaction has been applied and rendered
- waitForUpdate
Function - Returns a `Promise` that resolves once any pending changes have been rendered.
- download
Function - Starts a browser-based image download for the given `AgChartInstance`. Returns a `Promise` that resolves once the download has been initiated.
- getImageDataURL
Function - Returns a base64-encoded image data URL for the given `AgChartInstance`.
- getState
Function - Returns a representation of the current state of the given `AgChartInstance`.
- setState
Function - Sets the state of the given `AgChartInstance` to the state provided.
- getSelection
Function - Retrieve the current selection. An error may be thrown if the chart state mutates whilst the selection items are being iterated. Returns An iterable of all selected items.
- setSelection
Function - Replaces the current selection.
- clearSelection
Function - Clear the entire selection state of all items on all series.
- isModuleRegistered
Function - Returns whether a module is available to this chart, either registered globally or passed to it via `AgCharts.create(options, { modules })`. Param moduleId the exported name of a module, such as `'LineSeriesModule'`. Bundles such as `AllCommunityModule` are not modules; `'QuadrantChartModule'` is accepted because the quadrant preset is only exported as a bundle.
- destroy
Function - Destroy the chart instance and any allocated resources supporting its rendering.
The following example demonstrates both create and update cases:
- Definition of an
optionsobject used to create the initial chart state. - Buttons that invoke mutations of the
optionsand trigger update of the chart state.
import {
AgAreaSeriesOptions,
AgChartLegendPosition,
AgChartOptions,
AgCharts,
AreaSeriesModule,
CategoryAxisModule,
LegendModule,
ModuleRegistry,
NumberAxisModule,
} from "ag-charts-community";
import { getData } from "./data";
function buildSeries(name: string): AgAreaSeriesOptions {
return {
type: "area",
xKey: "year",
yKey: name.toLowerCase(),
yName: name,
fillOpacity: 0.5,
};
}
const series = [
buildSeries("IE"),
buildSeries("Chrome"),
buildSeries("Firefox"),
buildSeries("Safari"),
];
const positions: AgChartLegendPosition[] = ["left", "top", "right", "bottom"];
const legend = {
position: positions[1],
};
ModuleRegistry.registerModules([
AreaSeriesModule,
CategoryAxisModule,
LegendModule,
NumberAxisModule,
]);
const options: AgChartOptions = {
title: {
text: "Browser Usage Statistics",
},
subtitle: {
text: "2009-2019",
},
data: getData(),
series,
legend,
};
options.container = document.getElementById("myChart");
const chart = AgCharts.create(options);
function reverseSeries() {
options.series = series.reverse();
chart.update(options);
}
function swapTitles() {
const oldTitle = options.title;
options.title = options.subtitle;
options.subtitle = oldTitle;
chart.update(options);
}
function rotateLegend() {
const currentIdx = positions.indexOf(legend.position ?? "top");
legend.position = positions[(currentIdx + 1) % positions.length];
options.legend = legend;
chart.update(options);
}
if (typeof window !== "undefined") {
// Attach external event handlers to window so they can be called from index.html
(<any>window).reverseSeries = reverseSeries;
(<any>window).swapTitles = swapTitles;
(<any>window).rotateLegend = rotateLegend;
}
export function getData(): any[] {
return [
{
year: "2009",
ie: 64.97,
firefox: 26.85,
safari: 2.79,
chrome: 1.37,
},
{
year: "2010",
ie: 54.39,
firefox: 31.15,
safari: 4.22,
chrome: 5.94,
},
{
year: "2011",
ie: 44.03,
firefox: 29.36,
safari: 5.94,
chrome: 15.01,
},
{
year: "2012",
ie: 34.27,
firefox: 22.69,
safari: 8.09,
chrome: 25.99,
},
{
year: "2013",
ie: 26.55,
firefox: 18.55,
safari: 10.66,
chrome: 31.71,
},
{
year: "2014",
ie: 17.75,
firefox: 14.77,
safari: 12.63,
chrome: 35.85,
},
{
year: "2015",
ie: 13.3,
firefox: 11.82,
safari: 13.79,
chrome: 42.27,
},
{
year: "2016",
ie: 8.94,
firefox: 8.97,
safari: 12.9,
chrome: 47.79,
},
{
year: "2017",
ie: 4.77,
firefox: 6.75,
safari: 14.54,
chrome: 51.76,
},
{
year: "2018",
ie: 3.2,
firefox: 5.66,
safari: 14.44,
chrome: 56.31,
},
{
year: "2019",
ie: 2.7,
firefox: 4.66,
safari: 15.23,
chrome: 61.72,
},
];
}
Delta Options Update Copy Link
AgChartInstance exposes the updateDelta() method to allow partial updates to a charts options.
To assist with state management, the complete applied options state can be retrieved by calling the getOptions() method on the AgChartInstance.
When updating series or axes options, the complete array must be supplied with all the properties for each item.
- updateDelta
Function - Update an existing `AgChartInstance` by applying a partial set of option changes. Returns a `Promise` that resolves once the requested change has been rendered. __Note:__ As each call could trigger a chart redraw, each individual delta options update should leave the chart in a valid options state. Also, multiple calls in quick succession could result in undesirable flickering. Callers should batch up and/or debounce changes to avoid unintended partial update renderings.
- getOptions
Function - Get the `AgChartOptions` representing the current chart configuration.
- updateDelta
Function - Update an existing `AgChartInstance` by applying a partial set of option changes. Returns a `Promise` that resolves once the requested change has been rendered. __Note:__ As each call could trigger a chart redraw, each individual delta options update should leave the chart in a valid options state. Also, multiple calls in quick succession could result in undesirable flickering. Callers should batch up and/or debounce changes to avoid unintended partial update renderings.
- getOptions
Function - Get the `AgChartOptions` representing the current chart configuration.
The following example demonstrates:
- Retrieving current Chart configuration via
getOptions(). - Mutation of the Chart configuration via
updateDelta().
import {
AgAreaSeriesOptions,
AgChartLegendPosition,
AgChartOptions,
AgChartTheme,
AgCharts,
AreaSeriesModule,
CategoryAxisModule,
LegendModule,
ModuleRegistry,
NumberAxisModule,
} from "ag-charts-community";
import { getData } from "./data";
function buildSeries(name: string): AgAreaSeriesOptions {
return {
type: "area",
xKey: "year",
yKey: name.toLowerCase(),
yName: name,
fillOpacity: 0.5,
};
}
const series = [
buildSeries("IE"),
buildSeries("Chrome"),
buildSeries("Firefox"),
buildSeries("Safari"),
];
const positions: AgChartLegendPosition[] = ["left", "top", "right", "bottom"];
const legend = {
position: positions[1],
};
ModuleRegistry.registerModules([
AreaSeriesModule,
LegendModule,
CategoryAxisModule,
NumberAxisModule,
]);
const options: AgChartOptions = {
title: {
text: "Browser Usage Statistics",
},
subtitle: {
text: "2009-2019",
},
data: getData(),
series,
legend,
};
options.container = document.getElementById("myChart");
const chart = AgCharts.create(options);
function reverseSeries() {
const series = chart.getOptions().series as AgAreaSeriesOptions[];
series!.reverse();
chart.updateDelta({ series });
}
function swapTitles() {
const { title, subtitle } = chart.getOptions();
chart.updateDelta({ title: subtitle, subtitle: title });
}
function rotateLegend() {
const position = chart.getOptions().legend!.position;
const currentIdx = positions.indexOf(position ?? "top");
const newPosition = positions[(currentIdx + 1) % positions.length];
chart.updateDelta({ legend: { position: newPosition } });
}
function changeTheme(event: Event) {
const theme = chart.getOptions()?.theme as AgChartTheme;
const markersEnabled =
theme?.overrides?.area?.series?.marker?.enabled ?? false;
chart.updateDelta({
theme: {
overrides: { area: { series: { marker: { enabled: !markersEnabled } } } },
},
});
const button = event.currentTarget as HTMLButtonElement;
button.setAttribute("aria-pressed", String(!markersEnabled));
}
if (typeof window !== "undefined") {
// Attach external event handlers to window so they can be called from index.html
(<any>window).reverseSeries = reverseSeries;
(<any>window).swapTitles = swapTitles;
(<any>window).rotateLegend = rotateLegend;
(<any>window).changeTheme = changeTheme;
}
export function getData(): any[] {
return [
{
year: "2009",
ie: 64.97,
firefox: 26.85,
safari: 2.79,
chrome: 1.37,
},
{
year: "2010",
ie: 54.39,
firefox: 31.15,
safari: 4.22,
chrome: 5.94,
},
{
year: "2011",
ie: 44.03,
firefox: 29.36,
safari: 5.94,
chrome: 15.01,
},
{
year: "2012",
ie: 34.27,
firefox: 22.69,
safari: 8.09,
chrome: 25.99,
},
{
year: "2013",
ie: 26.55,
firefox: 18.55,
safari: 10.66,
chrome: 31.71,
},
{
year: "2014",
ie: 17.75,
firefox: 14.77,
safari: 12.63,
chrome: 35.85,
},
{
year: "2015",
ie: 13.3,
firefox: 11.82,
safari: 13.79,
chrome: 42.27,
},
{
year: "2016",
ie: 8.94,
firefox: 8.97,
safari: 12.9,
chrome: 47.79,
},
{
year: "2017",
ie: 4.77,
firefox: 6.75,
safari: 14.54,
chrome: 51.76,
},
{
year: "2018",
ie: 3.2,
firefox: 5.66,
safari: 14.44,
chrome: 56.31,
},
{
year: "2019",
ie: 2.7,
firefox: 4.66,
safari: 15.23,
chrome: 61.72,
},
];
}
Waiting for Options Update Copy Link
Creation and updates happen asynchronously, but in some situations it may be useful to know when an update has been rendered.
To assist with this, AgChartInstance.update() and AgChartInstance.updateDelta() return Promises that resolve once rendering is complete.
Additionally AgChartsInstance.waitForUpdate() can be used after initial creation to understand when the first rendering of the newly created chart is complete.
Although rendering may be complete, browsers may not repaint until Javascript execution pauses.
Promises do not take animations into account, they resolve after the first rendering in an animation sequence.
This example demonstrates how these APIs can be used to continuously update a chart, with each update only being applied once the previous update has been rendered.
import {
AgCharts,
AllCommunityModule,
ModuleRegistry,
} from "ag-charts-community";
ModuleRegistry.registerModules(AllCommunityModule);
const options = {
title: { text: "Frameworks not supported" },
subtitle: { text: "Switch to Javascript" },
};
options.container = document.getElementById("myChart");
const chart = AgCharts.create(options);
import { random } from "./seededRandom";
let count = 0;
export function generateDatum() {
return { count: count++, value: random() * 100 };
}
export function getData() {
const result: { count: number; value: number }[] = [];
for (let i = 0; i < 100; i++) {
result[i] = generateDatum();
}
return result;
}
export function createSeededRandom(seed = 42): () => number {
let state = seed;
return () => {
state = (state * 16807) % 2147483647;
return (state - 1) / 2147483646;
};
}
export const random = createSeededRandom();
Destroying Charts Copy Link
Charts can be destroyed by using the AgChartInstance.destroy() method.
- destroy
Function - Destroy the chart instance and any allocated resources supporting its rendering.
- destroy
Function - Destroy the chart instance and any allocated resources supporting its rendering.