chart.jschart.js3

Chart.js - Pie chart calculate sum of visible values after legend click


Im using Chart.js to display a pie chart and its legend. When a user clicks on a legend label to disable\hide it I want to recalculate the sum total for all visible sections remaining in the pie chart.

I have overridden the default Legend Click Handler and am trying to do this in there - Im not sure if this is the place to do it but it seems logical to do so.

const defaultLegendClickHandler = Chart.defaults.plugins.legend.onClick;
const pieDoughnutLegendClickHandler = Chart.controllers.doughnut.overrides.plugins.legend.onClick;

const newLegendClickHandler = function (e, legendItem, legend) {
    const index = legendItem.datasetIndex;
    const type = legend.chart.config.type;

    if (type === 'pie' || type === 'doughnut') {
        pieDoughnutLegendClickHandler(e, legendItem, legend)
    } else {
        defaultLegendClickHandler(e, legendItem, legend);
    }

    let ci = legend.chart;
    //Iterate through visible values of a data set and sum them...????
               
};

enter image description here


Solution

  • You can interate throguh the data, check if it is hidden and if not add it to the total:

    const defaultLegendClickHandler = Chart.defaults.plugins.legend.onClick;
    const pieDoughnutLegendClickHandler = Chart.controllers.doughnut.overrides.plugins.legend.onClick;
    
    const newLegendClickHandler = function(e, legendItem, legend) {
      const index = legendItem.datasetIndex;
      const type = legend.chart.config.type;
    
      if (type === 'pie' || type === 'doughnut') {
        pieDoughnutLegendClickHandler(e, legendItem, legend)
      } else {
        defaultLegendClickHandler(e, legendItem, legend);
      }
    
      let ci = legend.chart;
      const sum = ci.data.datasets.reduce((acc, curr) => {
        curr.data.forEach((d, i) => {
          if (ci.getDataVisibility(i)) {
            acc += d;
          }
        });
    
        return acc
      }, 0)
      console.log(sum)
      // Do whatever you want with the total.
    };
    
    const options = {
      type: 'doughnut',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
          },
          {
            label: '# of Points',
            data: [7, 11, 5, 8, 3, 7],
            backgroundColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
          }
        ]
      },
      options: {
        plugins: {
          legend: {
            onClick: newLegendClickHandler
          }
        }
      }
    }
    
    const ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
    </body>