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>
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;
}
}
}
}]
Source:stackexchange.com