chartist.js pie chart with labels AND percentage on the pie
You must keep an array containing your labels, and use the labelInterpolationFnc
with two parameters to get index, and use it to get the proper label with percentage:
var animals = ['Dog', 'Cat', 'Cow', 'Snake'];
var data = {
series: [5, 3, 4]
};
var sum = function(a, b) {
return a + b
};
new Chartist.Pie('.ct-chart', data, {
labelInterpolationFnc: function(value, idx) {
var percentage = Math.round(value / data.series.reduce(sum) * 100) + '%';
return animals[idx] + ' ' + percentage;
}
});
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<link href="://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css" rel="stylesheet"/>
<div class="ct-chart ct-perfect-fourth"></div>
Note that we must not use the labels
in your data array (only the series), otherwise the value parameter in labelInterpolationFnc
will be filled with the label instead of the value, so we couldn't calculate the percentage.