问题
Currently, in amchart4, the legends can be used to show / hide the target series on click. I would like the behaviour wherein on clicking on the legend:
- Do not hide the clicked series.
- Hide all other series except the one that was clicked so as to show only the seires whose legend that was clicked.
This question is on the back of an older question targetting amcharts3. However, since v4 is significantly different from v3, the answer does not work.
Based on the documentation here, it appears that the below should work:
series1.events.on("hidden", function() {
series2.hide();
series3.hide();
// but when I run series1.show() in order to mimic series1 to not hide, I get a max call size exceeded msg
});
Further to that, according to this, one can outright disable the toggle on the legends - but it works at the cart level and not at the series level.
Thanks.
Update: Follow up is available on GitHub. Posting the update here for the sake of completeness.
@zeroin 's answer works perfectly. I just needed it to be modified a bit more to have it working for the below scenario.
How do I re-enable all the series again? In the graph I'm building, I have a series called 'allTraffic' and multiple other series.
- AllTraffic should never get hidden.
- When I click on any of the other series apart from AllTraffic, hide the other series apart from AllTraffic and the series whose legend has been clicked.
Reset everything (bring back all the series) when AllTraffic's legend is clicked.
chart.legend.itemContainers.template.togglable = false;
chart.legend.itemContainers.template.events.on("hit", function(event) { var target = event.target; chart.legend.itemContainers.each(function(item) { if (target.dataItem.dataContext.name != 'All traffic' && item.dataItem.dataContext.name != 'All traffic') { console.log("clicked other: ", target.dataItem.dataContext.name); item.isActive = true; item.dataItem.dataContext.hide(); } if (target.dataItem.dataContext.name == 'All traffic') { console.log("Clicked all traffic"); item.isActive = false; item.dataItem.dataContext.show(); } }); target.isActive = false; target.dataItem.dataContext.show(); })
回答1:
Here is how you do it: https://codepen.io/team/amcharts/pen/285b315ff30a2740fdbf72f27230711c
To avoid SO you need to make itemContainers not togglable:
chart.legend.itemContainers.template.togglable = false;
chart.legend.itemContainers.template.events.on("hit", function(event){
var target = event.target;
chart.legend.itemContainers.each(function(item){
if(item != target){
item.isActive = true;
item.dataItem.dataContext.hide();
}
})
target.isActive = false;
target.dataItem.dataContext.show();
})
来源:https://stackoverflow.com/questions/60221701/how-can-we-use-legends-as-filters-in-amcharts4