I've been working on creating a bar graph using amcharts and I'm trying to show the percentage on top of each bar. Here is the code snippet I have so far:
$.ajax({
url: "https://daturl",
contentType: "application/json; charset=utf-8",
type: "GET",
dataformat: "JSON",
async: false,
success: function (data) {
var amc = AmCharts.makeChart("chartdiv",
{
"type": "serial",
"dataProvider": data,
"categoryField": "name",
"startDuration": 1,
"categoryAxis": {
"gridPosition": "start"
},
"trendLines": [],
"graphs": [
{
"valueField": "count",
"fillColors": "#0095cc",
"type": "column",
"balloonText": "[[title]] of [[category]]:[[value]]",
"fillAlphas": 0.8,
"lineAlpha": 0.2,
"id": "AmGraph-1",
"title": "graph",
"labelText": " ",
//code for calculating percentage
"labelFunction": function (item, data) {
var total = 0;
console.log(data.length + " is the size of the data in long trips");
for (var i = 0; i < data.length; i++) {
total += data[i][item.graph.valueField];
}
var percent = Math.round((item.values.value / total) * 1000) / 10;
return percent + "%";
}
}],
"guides": [],
"valueAxes": [
{
"id": "ValueAxis-1",
"title": "Count",
"gridColor": "#FFFFFF",
"gridAlpha": 0.2
}
],
"categoryAxis": {
"title": "Zone",
"gridPosition": "start",
"gridAlpha": 0,
"tickPosition": "start",
"tickLength": 20,
"labelRotation": 24
},
"gridAboveGraphs": true,
"allLabels": [],
"balloon": {},
"legend": {
"enabled": true,
"useGraphSettings": true
},
"titles": [
{
"id": "Title-1",
"size": 15,
"text": "graph"
}
]
});
},
error: function () {
alert("error while plotting down graph ");
}
});
When I run the code, the graphs display correctly but the percentages are showing up as NaN
. Any insights would be greatly appreciated.