1๐
โ
I think you could add the value as part of the returned value of the callback.
Furthermore, using a doughnut/pie controller, you can access to the dataset meta data where you have already the total value therefore you could avoid to sum all values everytime.
const data = {
labels: ['America', 'China', 'Dubai', 'India'],
datasets: [
{
label: 'Work Orders',
data: [10, 50, 5, 2],
backgroundColor: [
'#00CF9B',
'#E55B5E',
'#FFD366',
'#5A9ED4',
],
borderWidth: 0,
},
],
};
const options = {
plugins: {
legend: {
position: 'right'
},
datalabels: {
display: 'auto',
color: 'black',
font: {
weight: 'bold'
},
formatter: (value, ctx) => {
const total = ctx.chart.getDatasetMeta(0).total;
let percentage = (value * 100 / total).toFixed(2) + "%";
return percentage + '(' + value + ')';
},
}
}
}
const ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
type: 'pie',
plugins: [ChartDataLabels],
data,
options
});
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
<script src="https://npmcdn.com/chart.js@latest/dist/chart.umd.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.2.0/dist/chartjs-plugin-datalabels.min.js"></script>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"></canvas>
</div>
Source:stackexchange.com