This is a demo tutorial. While there is no step-by-step commentary available (yet), the live demo below is fully functional. Feel free to open it for full source code.
This demo shows how we can use events on a Legend to "inverse" toggle behavior of Pie chart's legend by showing only clicked sliced, while hiding the rest of the slices.
Code
let legend = chart.children.push(am5.Legend.new(root, {
centerX: am5.percent(50),
x: am5.percent(50),
layout: root.horizontalLayout,
clickTarget: "none"
}));
let currentlySelected;
legend.itemContainers.template.events.on("click", function(ev) {
const targetDataItem = ev.target.dataItem.dataContext;
const showAll = currentlySelected === targetDataItem ? true : false;
currentlySelected = targetDataItem;
const series = targetDataItem.component;
am5.array.each(series.dataItems, function(seriesDataItem) {
if (seriesDataItem === targetDataItem || showAll) {
seriesDataItem.show();
}
else {
seriesDataItem.hide();
}
});
if (showAll) {
currentlySelected = undefined;
}
});
var legend = chart.children.push(am5.Legend.new(root, {
centerX: am5.percent(50),
x: am5.percent(50),
layout: root.horizontalLayout,
clickTarget: "none"
}));
var currentlySelected;
legend.itemContainers.template.events.on("click", function(ev) {
var targetDataItem = ev.target.dataItem.dataContext;
var showAll = currentlySelected === targetDataItem ? true : false;
currentlySelected = targetDataItem;
var series = targetDataItem.component;
am5.array.each(series.dataItems, function(seriesDataItem) {
if (seriesDataItem === targetDataItem || showAll) {
seriesDataItem.show();
}
else {
seriesDataItem.hide();
}
});
if (showAll) {
currentlySelected = undefined;
}
});
Example
See the Pen Inverse-toggling Pie Chart slices via legend by amCharts team (@amcharts) on CodePen.