[Chartjs]-Chart.js โ€“ Pie chart calculate sum of visible values after legend click

1๐Ÿ‘

โœ…

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>

Leave a comment