Activate/deactivate a pie slice on legend click instead of toggling

Normally, when you click an item in PieChart's legend, relative slice is hidden or revealed. This quick tutorial will show you how to make the slice activate/deactivate (pull out/in) instead.

Setting up

To make this work we'll have to do two things:

  • Disable regular toggling of the items.
  • Add custom event that toggles isActive state of the related slice.

The below code will do just that:

chart.legend.itemContainers.template.togglable = false;
chart.legend.itemContainers.template.events.on("hit", function(ev) {
  var slice = ev.target.dataItem.dataContext.slice;
  slice.isActive = !slice.isActive;
});
chart.legend.itemContainers.template.togglable = false;
chart.legend.itemContainers.template.events.on("hit", function(ev) {
  var slice = ev.target.dataItem.dataContext.slice;
  slice.isActive = !slice.isActive;
});
{
  // ...
  "legend": {
    // ...
   "events": {
     "hit": function(ev) {
       var slice = ev.target.dataItem.dataContext.slice;
       slice.isActive = !slice.isActive;
     }
   }
}

Example

See the Pen amCharts 4: Activate/deactivate a pie slice on legend click instead of toggling by amCharts team (@amcharts) on CodePen.

Restricting to one pulled slice

Let's mod our code further to allow only one pulled out slice at a time.

chart.legend.itemContainers.template.events.on("hit", function(ev) {
  let slice = ev.target.dataItem.dataContext.slice;
  pieSeries.slices.each(function(item) {
    if (item != slice) {
      item.isActive = false;
    }
    else {
      slice.isActive = !slice.isActive;
    }
  });
});
chart.legend.itemContainers.template.events.on("hit", function(ev) {
  var slice = ev.target.dataItem.dataContext.slice;
  pieSeries.slices.each(function(item) {
    if (item != slice) {
      item.isActive = false;
    }
    else {
      slice.isActive = !slice.isActive;
    }
  });
});
{
  // ...
  "legend": {
    // ...
   "events": {
     "hit": function(ev) {
        var slice = ev.target.dataItem.dataContext.slice;
        pieSeries.slices.each(function(item) {
         if (item != slice) {
           item.isActive = false;
         }
         else {
           slice.isActive = !slice.isActive;
         }
       }); 
     }
   }
}

See the Pen amCharts 4: Activate/deactivate a pie slice on legend click instead of toggling by amCharts team (@amcharts) on CodePen.

Related tutorials