Chartie.js pie chart with tags. And percentage on pie.

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 a pie chart. I want to add percentage values ​​to parts. http://i.stack.imgur.com/SiIKb.png

Here ( https://gionkunz.imtqy.com/chartist-js/examples.html ) is an example with percentages in a pie. But this only works if I DO NOT add tags.

Adding labels to the data (for example, labels: ['Dog', 'Cat', 'Cow', 'Snake',],) displays "NaN%".

I want to see the percentages in the pie itself, and also put labels (for legend) in the data.

Is it possible?

+4
source share
2 answers

You must save the array containing your labels and use labelInterpolationFncwith two parameters to get the index and use it to get the corresponding label with a 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;
  }
});

Please note that we should not use labels(only a series) in your data array, otherwise the value parameter in labelInterpolationFncwill be filled with a label instead of a value, so we could not calculate the percentage.

+5
source

what you need to do to create a shortcut yourself. You need to create a string like [Labeltext] + '| '+ [Share]

In my case, I created a variable that contains the total amount of all elements of the pie ... called [griall] ....

Then there is this function that calculates the fractions ...

		function calcProz(value, griall) {
			return Math.round(value / griall * 100) + '%';
		};
Run codeHide result

, , , , ...

		chartlabels[i]=dbresult[i].use + ' | ' + calcProz(dbresult[i].gri,griall);
Hide result

dbresult [i].use - , dbresult [i].gri - , ( )

, , ...

var data = {
				series: chartdata,
		//		series: [25,16,15, 14, 4,2,1]
				labels: chartlabels
		
		};
Hide result
0

All Articles