I have a map that is based on this example from the amCharts website. I want to add a clickable shared legend across these pie charts. So that whenever someone clicks a legend element, it updates all the pie charts to show only "active" slice values. I have tried to create a custom legend in this way:
// Setting up legend
var legend = new am4maps.Legend();
legend.parent = chart.chartContainer;
legend.background.fill = am4core.color("#000");
legend.background.fillOpacity = 0.05;
legend.y = am4core.percent(100);
legend.verticalCenter = "bottom";
legend.padding(10,15,10,15)
legend.data = [{
"name": "Category #1",
"fill": chart.colors.getIndex(0)
}, {
"name": "Category #2",
"fill": chart.colors.getIndex(1)
}, {
"name": "Category #3",
"fill": chart.colors.getIndex(2)
}, {
"name": "Category #4",
"fill": chart.colors.getIndex(2)
}];
// Does something when legend marker is clicked
legend.itemContainers.template.events.on("hit", function(ev) {
var index = ev.target.dataItem.index;
if (ev.target.isActive) {
//????.hide();
}
else {
//????.show();
}
})
In this example (codepen) I create a custom legend and a function which triggers when legend markers are 'hit'. I have tried many different things in this function, but have not gotten far. I simply don't know how to access the different slice elements (indicated with '????') of the charts for manipulation on legend marker 'hit'.
Another possible route I have seen is to plug it directly into the chart in some way. But this only seems to work for single pie charts. (Shown here) This example also shows exactly the kind of behaviour I want. Problem is that I want ONE legend, not one for every pie.
I used your first approach, using a custom legend.
You can use the hidden property on your chart to hide specific categories.
pieSeriesTemplate.dataFields.hidden = "hidden";
You can now add an event to toggle this property on all pie chart data. Use the "up"
event, because event.target.isActive
is updated after the "hit"
event is called.
legend.itemContainers.template.events.on("up", (ev) => {
var category = ev.target.dataItem.dataContext.name;
pieSeries.data.forEach(item => item.pieData.find(i => i.category === category).hidden = !ev.target.isActive);
pieSeries.validateData();
});
Here I forked and updated your code pen. Hope that helps.