Toggling multiple series with a single legend item

This tutorial will show how you can toggle several Series at once, with a single Legend item.

Base chart

Let's start with a basic chart with three Line series.

See the Pen amCharts 4: Toggling multiple series with a single legend item by amCharts team (@amcharts) on CodePen.0

Each Series has its own entry in the Legend. Click any of those will toggle its corresponding Series on and off.

Suppose, we need to have just a single item in Legend. Clicking it would toggle all three of the series.

Hiding series from legend

This part's pretty easy: if we don't a series to appear in legend, we set its hiddenInLegend property to true.

Since we need to hide only the second and third item, we set hiddenInLegend for them, but not for the first series.

// ...
series2.hiddenInLegend = true;

// ...
series3.hiddenInLegend = true;
// ...
series2.hiddenInLegend = true;

// ...
series3.hiddenInLegend = true;
{
// ...
"series": [{
// ...
}, {
// ...
"hiddenInLegend": true
}, {
// ...
"hiddenInLegend": true
}]
}

See the Pen amCharts 4: Toggling multiple series with a single legend item by amCharts team (@amcharts) on CodePen.0

That took care of the two legend items. However clicking the remaining one just hides a single series.

Toggling multiple series

We need to set up a code that hides remaining two series when the first one is hidden, and vice versa: bring them back up when the first one is switch back on.

For that series events "hidden" and "shown" seems to be perfect.

series1.events.on("hidden", function() {
series2.hide();
series3.hide();
});

series1.events.on("shown", function() {
series2.show();
series3.show();
});
series1.events.on("hidden", function() {
series2.hide();
series3.hide();
});

series1.events.on("shown", function() {
series2.show();
series3.show();
});
{
// ...
"series": [{
// ...
"events": {
"hidden": function(ev) {
var chart = ev.target.baseSprite;
chart.series.getIndex(1).hide();
chart.series.getIndex(2).hide();
},
"shown": function(ev) {
var chart = ev.target.baseSprite;
chart.series.getIndex(1).show();
chart.series.getIndex(2).show();
}
}
}, {
// ...
"hiddenInLegend": true
}, {
// ...
"hiddenInLegend": true
}]
}

That's about it. Now, when you click our only legend item, all three of the series will toggle.

See the Pen amCharts 4: Toggling multiple series with a single legend item by amCharts team (@amcharts) on CodePen.0

Separate toggle button

If, however, we would like to still have individual toggling control for each series, but also a button that toggles them all, we could do that by adding an additional series without any data, that would serve as this "global toggle" button.

See the Pen amCharts 4: Toggling multiple series with a single legend item by amCharts team (@amcharts) on CodePen.0