4

I am doing data visualizations with react, react-chartjs-2, and chart.js version 2.2.1. There is a possibly related answer to this question here (look for 17.06.16 update), but I'm not sure what Chart.pluginService.register is or whether it is compatible with React. So far it hasn't worked for me.

I am simply looking to place a label inside the doughnut that is the sum of all data subsets. I assume this is nested somewhere in the doughnut chart's options, but I haven't found it yet.

Community
  • 1
  • 1
Kwhitejr
  • 2,206
  • 5
  • 29
  • 49
  • Did you find a solution to this? – LucaSpeedStack Mar 31 '17 at 05:32
  • Negative. I had to make a separate value using the same data on my component – Kwhitejr Mar 31 '17 at 19:37
  • Please refer below code. This is perfectly work. [https://stackoverflow.com/questions/54040320/pass-context-to-options-on-react-chartjs-2](https://stackoverflow.com/questions/54040320/pass-context-to-options-on-react-chartjs-2) – donkey Mar 15 '23 at 08:23

1 Answers1

5

In react-chartjs-2 you can access the datasets through chart.config.data.datasets.

So for:

data = {
    labels: [
        'Red',
        'Green',
        'Yellow'
    ],
    datasets: [{
        data: [300, 50, 100],
    ...

Inside the draw callback in Chart.helpers.extend you can use:

var sum = 0;
for (var i = 0; i < this.chart.config.data.datasets[0].data.length; i++) {
   sum += this.chart.config.data.datasets[0].data[i];
}

Here's an example Codepen: http://codepen.io/anon/pen/xqMQQB?editors=1010

K Scandrett
  • 16,390
  • 4
  • 40
  • 65