1👍
✅
First get the total
for the data we can use Javascript’s reduce
method
const total = vm.data.reduce((a, b) => a+b, 0);
Now update the label callback to calculate the percentages.
callbacks: {
label: (ttItem,data) => (`${data.labels[ttItem.index]}: ${Math.round(data.datasets[ttItem.datasetIndex].data[ttItem.index]/total*10000)/100}%`)
}
Note, in the above code I’ve rounded the percentages to show 2 decimal points, you might want to change that.
Here’s the entire code for MainController.
function MainController($scope, $timeout) {
var vm = this;
vm.labels = ["Download Sales", "In-Store Sales", "Mail-Order Sales", "Other Sales"];
vm.data = [360, 507, 207, 900];
const total = vm.data.reduce((a, b)=> a+b, 0);
vm.options = {
legend: {
display: true,
position: 'bottom'
},
tooltips: {
callbacks: {
label: (ttItem,data) => (`${data.labels[ttItem.index]}: ${Math.round(data.datasets[ttItem.datasetIndex].data[ttItem.index]/total*10000)/100}%`)
}
},
cutoutPercentage: 60,
tooltipEvents: [],
tooltipCaretSize: 0,
showTooltips: true,
onAnimationComplete: function() {
self.showTooltip(self.segments, true);
}
}
}
Source:stackexchange.com