Reputation: 385
Below code renders charist charts with label and appropriate value I want to append computed percentage to each lable i.e
c_labels = ["one", "two", "three", "four"];
c_series = [10, 30, 50, 90];
options = {}
new Chartist.Pie('.ct-chart', {
labels: c_labels,
series: c_series,
}, options);
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<link href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css" rel="stylesheet" />
<div class="ct-chart ct-perfect-fourth"></div>
Upvotes: 2
Views: 1170
Reputation: 2139
So you want to show the percentage in each labels. That only needs a simple string formatting, I pressume.
What you do is get the sum of your series using Array.reduce
. (let's call it total
)
Next, for each item in your series, divide it by the total
then multiply by 100. That way, you get the percentage of each series over the total
:
var c_labels = ["one", "two", "three", "four"],
c_series = [10, 30, 50, 90],
newLabels = [];
var total = c_series.reduce(function(a, b) {
return a + b;
}, 0);
for (var i = 0; i < c_series.length; i++) {
var percentage = ((c_series[i] / total) * 100).toFixed(2),
newLabel = c_labels[i] + '(' + percentage + '%)'; //simple string concatenation
//assign the new string to our new labels
newLabels[i] = newLabel;
}
new Chartist.Bar('.ct-chart', {
labels: newLabels,
series: [c_series] //YOUR SERIES SHOULD BE INSIDE AN ARRAY!
}, {
stackBars: true,
axisY: {
labelInterpolationFnc: function(value) {
return (value / 1000) + 'k';
}
}
});
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<link href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css" rel="stylesheet" />
<div class="ct-chart ct-perfect-fourth"></div>
Note:
Using toFixed
automatically rounds off the number. You can remove it if you want but I added it so we can get 2 decimal precision. You can also try toPrecision
or a combination. Just find samples on the web, there's a lot out there, especially SO.
One more thing,
MAKE SURE YOUR SERIES AND LABELS ARE OF THE SAME LENGTH.
You might need to check for c_labels[i] !== null || c_labels[i] !== undefined
.
Upvotes: 2
Reputation: 89
your code have many errors. Its needs to be correct as below
var c_labels = ["one", "two", "three", "four"];
var c_series = [5.55, 16.66, 27.77, 50];
var options = {
width: 300,
height: 200
};
new Chartist.Bar('.ct-chart', {
labels: c_labels,
series: [c_series]
}, options);
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<link href="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.css" rel="stylesheet" />
<div class="ct-chart ct-perfect-fourth"></div>
Upvotes: 2