I want to create a pie chart with chartist.js with labels (which are shown in the legend) AND also with percentages in the pie itself.
This is the pie chart. I want to add percentage values to the pieces. http://i.stack.imgur.com/SiIKb.png
Here (https://gionkunz.github.io/chartist-js/examples.html) is an example with percentages in the pie. But this only works if I do NOT add labels.
Adding labels to the data (e.g. labels: ['Dog','Cat','Cow','Snake',],) results in "NaN%" display.
I want to see the percentages in the pie itself and also put labels (for the legend) into the data.
Is this possible?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With