Skip to content

Dynamically adding and removing Series

This tutorial will show how you can dynamically add and remove series to the chart.

Adding a series to the chart is as simple as pushing a series object into chart’s series list:

let series = new am4charts.LineSeries();
// configure series
chart.series.push(series);
var series = new am4charts.LineSeries();
// configure series
chart.series.push(series);

The chart will take care of the rest. No further action is necessary.

Here’s a working example:

Open in CodePen

When we were adding series to the chart, we were pushing series objects directly to chart’s series list.

Predictably, removing series will involve removing it from series.

Since it’s a List (Array on steroids), we can use its method removeIndex():

chart.series.removeIndex(0);

chart.series.removeIndex(0);

The above will remove the first series from the chart, and will return the removed item.

At this point removed series should disappear from the map without any further action.


What if don’t know the index of particular series, but have a reference to series object?

We can use List’s indexOf() method to find the index, then proceed as per above:

chart.series.removeIndex(
chart.series.indexOf(series_to_remove)
);

chart.series.removeIndex(
chart.series.indexOf(series_to_remove)
);


Important thing to note, that while series is removed from the chart, it continues its (orphaned) existence.

Removing a lot of series might result in memory leaks.

As a good housekeepers we need to dispose stuff that is no longer needed.

Since removeIndex() returns the actual object, it’s easy to just call dispose() on it and call it a day:

chart.series.removeIndex(
chart.series.indexOf(series_to_remove)
).dispose();

chart.series.removeIndex(
chart.series.indexOf(series_to_remove)
).dispose();

Open in CodePen