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.