2👍
✅
There doesn’t seem to be any native way to show the percentages, but it’s quite straightforward to calculate and set them as the labels:
const data = [1, 2, 3],
// ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
total = data.reduce((accumulator, currentValue) => accumulator + currentValue),
// ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
labels = data.map(value => Math.round((value / total) * 100) + '%');
new Chart(document.getElementById('chart'), {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
data: data
}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="75"></canvas>
(Note: the use of Math.round()
could cause certain number sets not to equal 100% when summed.)
1👍
If you already have an array of legends, you can add the percentage to it with this code. Here i is the index of the current element in the array.
data=[2,4,5,7];
legend=['A','B','C','D']
total = data.reduce((accumulator, currentValue) => parseInt(accumulator) + parseInt(currentValue));
labelsvalues = data.map(function(value,i){
let p= Math.round((value / total) * 100) + '%';
return legend[i]+' '+p;
});
Source:stackexchange.com