5

I am trying to add percentage to pie chart in ChartJS 3.2.1

All the answers and code I have found from extensive searching reference ChartJS version 1 or 2.

Including This question and This question and this question which all fail or do not actually change any tooltip display.

There is numerous reference to https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0 but this doesn't work on ChartJS v3; I have installed the ChartJS Datalabels for Version 3 from here:

https://github.com/chartjs/chartjs-plugin-datalabels/releases/tag/v2.0.0

but using This answer still does not work.

I can not see on the ChartJS Datalabels Plugin documentation how to implement what I'm looking for.

I am looking for the percentage for each piece of the pie to be shown on the tooltip hover OR on the pie piece itself, but not on the label/legend.

I can't see anything on the ChartJS Tooltip documentation about how to actually edit the textual content of the tooltip.

So, my code:

JS:

    var dnct1 = document.getElementById('DoeNut1');
    var myChart1 = new Chart(dnct1, {
    type: 'doughnut',
    data: {
          labels: ["Scotland and Northern Ireland","North East England","North West","Midlands","East Anglia","South England"],
          datasets: [{
               label: ["Scotland and Northern Ireland","North East England","North West","Midlands","East Anglia","South England"],
               data: ["510","887","720","837","993","774","977"],
               borderWidth: 0,
               hoverOffset: 5,
               backgroundColor: ['#F3AC16','#9F9F9F','#FF3355', '#55EE22','#354D73','#553FCF'],
               cutout: 0
          }]
    },
options: {
   tooltips: {
         enabled: true,
   },
   layout: {
        padding: {
            bottom: 25
         }
   },
   plugins: {
        /** Imported from a question linked above. 
            Apparently Works for ChartJS V2 **/
        datalabels: {
            formatter: (value, dnct1) => {
                let sum = 0;
                let dataArr = dnct1.chart.data.datasets[0].data;
                dataArr.map(data => {
                    sum += data;
                });
                let percentage = (value*100 / sum).toFixed(2)+'%';
                return percentage;
            },
            color: '#ff3'
        }
    }
}
});
 

HTML:

<div class='chartBox'>
     <h2>Title</h2>
     <canvas id='DoeNut1'></canvas>
</div> 

The above no browser console errors are returned and all charts display correctly but the tooltips don't show any percentages. I can't see what's wrong.

Martin
  • 22,212
  • 11
  • 70
  • 132
  • @LeeLenalee I suspected that may have been the case, but there was no other changes. No worries `:-)` – Martin Jul 01 '21 at 11:39

2 Answers2

9

If you are using ChartJS v3 then I got it to work without any additional plugins. I overrode the tooltip at the dataset level.

datasets: [{
    label: 'Industries',
    data: [1, 5, 10, 14, 15],
    tooltip: {
        callbacks: {
            label: function(context) {
                let label = context.label;
                let value = context.formattedValue;

                if (!label)
                    label = 'Unknown'

                let sum = 0;
                let dataArr = context.chart.data.datasets[0].data;
                dataArr.map(data => {
                    sum += Number(data);
                });

                let percentage = (value * 100 / sum).toFixed(2) + '%';
                return label + ": " + percentage;
            }
        }
    }
}]
Andrew Schultz
  • 4,092
  • 2
  • 21
  • 44
4

To use the datalabels plugin you will need to register it also please read the migration guide (https://www.chartjs.org/docs/master/getting-started/v3-migration.html) first because you are using v2 syntax for your tooltip for example which wont work.

To get the percentage in the tooltip you can use any of the callbacks (https://www.chartjs.org/docs/master/configuration/tooltip.html#tooltip-callbacks) see example below for datalabels and the footer callback to display the percentages:

var dnct1 = document.getElementById('DoeNut1');
var myChart1 = new Chart(dnct1, {
  type: 'doughnut',
  data: {
    labels: ["Scotland and Northern Ireland", "North East England", "North West England", "North Wales and West Midlands", "East Midlands and East Anglia", "South Wales and South West England", "South East England"],
    datasets: [{
      label: ["Scotland and Northern Ireland", "North East England", "North West England", "North Wales and West Midlands", "East Midlands and East Anglia", "South Wales and South West England", "South East England"],
      data: ["510", "887", "720", "837", "993", "774", "977"],
      borderWidth: 0,
      hoverOffset: 5,
      backgroundColor: ['#F3AC16', '#9F9F9F', '#FF3355', '#55EE22', '#354D73', '#666633', '#553FCF'],
      cutout: 0
    }]
  },
  options: {
    layout: {
      padding: {
        bottom: 25
      }
    },
    plugins: {
      tooltip: {
        enabled: true,
        callbacks: {
          footer: (ttItem) => {
            let sum = 0;
            let dataArr = ttItem[0].dataset.data;
            dataArr.map(data => {
              sum += Number(data);
            });

            let percentage = (ttItem[0].parsed * 100 / sum).toFixed(2) + '%';
            return `Percentage of data: ${percentage}`;
          }
        }
      },
      /** Imported from a question linked above. 
          Apparently Works for ChartJS V2 **/
      datalabels: {
        formatter: (value, dnct1) => {
          let sum = 0;
          let dataArr = dnct1.chart.data.datasets[0].data;
          dataArr.map(data => {
            sum += Number(data);
          });

          let percentage = (value * 100 / sum).toFixed(2) + '%';
          return percentage;
        },
        color: '#ff3',
      }
    }
  },
  plugins: [ChartDataLabels]
});
<body>
    <canvas id="DoeNut1" width="600" height="400"></canvas>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0-rc.1/chartjs-plugin-datalabels.js" ></script>
</body>
LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
  • Ah I had read about registering but had misunderstood that because it was inline in the `options` menu that it could not be registered and so would be used as is. – Martin Jul 01 '21 at 11:44
  • All my graphs on the same page now have labels on their elements, how can I remove these labels? The tooltip works perfectly. – Martin Jul 01 '21 at 12:02
  • Instead of globally registering the plugin, you can only register it to the chart you want it to work on, see updated example – LeeLenalee Jul 01 '21 at 12:04