This tutorial will show how you can dynamically add and remove series to the chart.
Adding series
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.
NOTE The above statement might not be true, if besides series, you're also modifying the chart's data to feed the series. In such case you might also need to call chart.invalidateData()
so that chart parses the new data.
Here's a working example:
See the Pen amCharts V4: Adding series by amCharts (@amcharts) on CodePen.
Removing series
Removing by index
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.
Removing by reference
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) );
Disposing removed series
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();
See the Pen amCharts V4: Removing series by amCharts (@amcharts) on CodePen.