percentage not shown in Amcharts - javascript

I am plotting a bar graph with amcharts and I wanted to display the percentage on the top of the bar.So below is the code:
$.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": " ",
//the percentage calculation function
"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 ");
}
});
So when I run the code the graphs are plotting but the percentages are not shown.Instead they show as NaN. Any help is appreciated

You're using the labelFunction wrong. You can see in the documentation, that the parameters given are a reference to GraphDataItem and the formatted label text.
In your for-loop you actually do total += " "[0]["value"] which results in total += undefined and cause total to be NaN. That's where to wrong labels come from.
You could access the full dataSet via item.graph.data and make a correct calculation with this.
My suggestion though would be, that you move that for-loop to another place in your script. You basically just sum up the data values over and over again, whenever the graph is drawn. This means this loop runs several hundred to thousand times when you are just resizing the graph. You could just calculate the total sum once and use it in the labelFunction.

Related

get the range values from AmCharts

I have an AmCharts working, this is the code:
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"precision":"3",
"decimalSeparator": ",",
"thousandsSeparator": ".",
"legend": {
"horizontalGap": 10,
"maxColumns": 3,
"position": "top",
"useGraphSettings": false,
"markerSize": 10,
"marginTop": 20,
"autoMargins":true,
"forceWidth":true,
"valueAlign":"right",
"labelWidth":85,
"valueWidth":85
},
"dataProvider": response,
"synchronizeGrid":true,
"valueAxes": [{
"axisAlpha": 0,
"position": "left",
"title": "Activos"
}],
/*"startDuration": 0.5,*/
"graphs": graphs,
"chartScrollbar": {},
"chartCursor": {
"cursorPosition": "mouse"
},
"categoryField": "diahora",
"categoryAxis": {
/*"parseDates": true,*/
"gridPosition": "start",
"axisColor": "#DADADA",
/*"minorGridEnabled": true*/
},
"export": {
"enabled": true,
"position": "top-right",
"class": "export-main",
"menu": [ {
"title": "Exportar el gráfico a archivo de imagen",
"label": "Descargar",
"menu": [ "PNG", "JPG", "PDF" ]
}]
}
});
I'm calling it with ajax with:
$.get(url, function(response){
So, I need to get the 2 values of the range of X of the graph that is being rendered on the browser after a zoom, any idea?
For example, when the graph starts, the range of the axis x are 0 and 100. If I zoom into some range, for example 40 and 60, I need to retrieve those values (40 and 60) because I will use them for another things in the page.
So, how could I save those ranges after every ajax call?
AmCharts provides the zoomed event, which gives you the start and end indices/values. You can use that and store the values for whatever you need, e.g.
AmCharts.makeChart("chartdiv", {
// ...
listeners: [{
event: "zoomed",
method: function(e) {
//e.startIndex and e.endIndex gives you the indicies in the dataProvider
//e.startValue and e.endValue gives you the start and end values
//e.startDate and e.endDate gives you the start and end dates if you're using parseDates
}
}]
});
Note that zoomed is also called on the initial load. If you don't want to capture the initial start/end values, you might need to keep track of the first load before storing those values on subsequent zoom events.

Amchart Dont show data where value =0

Im working in a graph where data comes from server like Object's Array.
I dont need some data to show in my graph, data where number=0, and i want to know if amchart have some function to dont show this.
Here is an example of the code:
var data =[
{'number':1, 'date':'11:00-11:59', 'duration': 3},
{'number':2, 'date':'12:00-12:59', 'duration':6},
{'number':4, 'date':'13:00-13:59', 'duration':12},
{'number':8, 'date':'14:00-14:59', 'duration':8},
{'number':0, 'date':'14:00-14:59', 'duration':0}
];
var chart = AmCharts.makeChart("chartdiv", {
"theme": "light",
"type": "serial",
"startDuration": 2,
"dataProvider": data,
"valueAxes": [{
"id": "number",
"position": "left",
"title": "N Llamadas"
},{
"id": "durationAxis",
"position": "right",
"title": "duration"
}],
"graphs": [{
"balloonText": "[[category]]: <b>[[value]]</b>",
"fillColorsField": "color",
"fillAlphas": 1,
"lineAlpha": 0.1,
"type": "column",
"valueField": "number"
},{
"bullet": "square",
"bulletBorderAlpha": 1,
"bulletBorderThickness": 1,
"dashLengthField": "dashLength",
"legendValueText": "[[value]]",
"title": "duration",
"fillAlphas": 0,
"valueField": "duration",
"valueAxis": "durationAxis"
}],
"depth3D": 20,
"angle": 30,
"chartCursor": {
"categoryBalloonEnabled": false,
"cursorAlpha": 0,
"zoomable": false
},
"categoryField": "date",
"categoryAxis": {
"gridPosition": "start",
"labelRotation": 0
},
"export": {
"enabled": true
}
});
In this case i dont want to show the last item of the array because number is 0, i shouldnt create a new array for reasons project.
Thanks in advance
Not showing a graph object when a value is 0 is pretty much impossible without modifying the array due to the bullets of the line chart (you can hide a column using alphaField, but you can't remove the bullet). You can write an init handler that nulls out zero values so that the chart doesn't show the point or column at all upon chart initialization:
//Nulls out any field that contains a zero, effectively hiding the point/column from the chart.
//Note that the category will still be visible if both points are null unless you null out that category as well.
AmCharts.addInitHandler(function(chart) {
var valueFields = chart.graphs.map(function(graph) {
return graph.valueField;
});
chart.dataProvider.forEach(function(dataItem) {
valueFields.forEach(function(valueField) {
if (dataItem[valueField] === 0) {
dataItem[valueField] = null;
}
})
})
}, ["serial"]);
Note that this will effect the data export (csv, xlsx, json) as well. If you want to re-add those zero values to the data export, you can use the processData callback in the export plugin to modify your data to re-add the zeroes:
"export": {
"enabled": true,
//re-add nulled out values as zeroes for data export:
"processData": function(data, cfg) {
var valueFields = this.setup.chart.graphs.map(function(graph) {
return graph.valueField;
});
data.forEach(function(dataItem) {
valueFields.forEach(function(valueField) {
if (dataItem[valueField] == null) {
dataItem[valueField] = 0;
}
});
});
return data;
}
}
Demo

Lines Graph are rendering as straight Lines in AM Charts

I am trying to draw Line Graph but these are rendering as a straight line in the bottom of graph area.I have added columns graphs too in it. they are showing properly but Lines Graph are not showing correct just a straight line. I have added the screenshot in the end. Please help.
This is my graph header
var header_graph = [{"balloonText":"[[title]] of [[category]]:[[value]]",
"fillAlphas":"1",
"id":"ProductA",
"title":"Produc A ",
"type":"SmoothedLine",
"valueField":"column2"}];
This is my graph data values
var data_graph = [{"category":"Jan",
"column1":"85", "column2":"24", "column3":"343",
"column4":"85", "column5":"31", "column6":"267",
"column7":"85", "column8":"19", "column9":"439"},......]
This is the whole script to generate the chart
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"depth3D": 2,
"startDuration": 1,
"theme": "light",
"precision": 2,
"valueAxes": [{
"id": "v1",
"title": "",
"position": "left",
"autoGridCount": false,
}, {
"id": "v2",
"title": "",
"gridAlpha": 0,
"position": "right",
"autoGridCount": false
}],
"graphs": header_graph ,
"chartScrollbar": {
"graph": "column2",
"oppositeAxis": false,
"offset": 30,
"scrollbarHeight": 50,
"backgroundAlpha": 0,
"selectedBackgroundAlpha": 0.1,
"selectedBackgroundColor": "#888888",
"graphFillAlpha": 0,
"graphLineAlpha": 0.5,
"selectedGraphFillAlpha": 0,
"selectedGraphLineAlpha": 1,
"autoGridCount": true,
"color": "#AAAAAA"
},
"chartCursor": {
"pan": true,
"valueLineEnabled": true,
"valueLineBalloonEnabled": true,
"cursorAlpha": 0,
"valueLineAlpha": 0.2
},
"categoryField": "category",
"categoryAxis": {
"parseDates": false,
"dashLength": 1,
"minorGridEnabled": true,
"gridPosition": "start"
},
"legend": {
"useGraphSettings": true,
"position": "bottom"
},
"balloon": {
"borderThickness": 1,
"shadowAlpha": 0
},
"export": {
"enabled": false
},
"dataProvider": data_graph
});
The chart is drawing your line at scale with respect to your chart's range of values and it looks like your values for the line are very small compared to the rest of your columns. It will look like a straight line near the bottom as a result of this.
You can use a valueScrollbar and let your users zoom in on the valueAxis/Y-axis so they can see the line better. It takes the same properties as a chartScrollbar as you can see in this demo from AmCharts:
"valueScrollbar": {
"autoGridCount": true,
"color": "#000000",
"scrollbarHeight": 50
},
Outside of that or making your valueAxis maximum smaller, there's not much else you can do.
(Off topic, you should make your values numbers, not strings.)
Edit
You can dynamically set the chart's maximum and minimum using addInitHandler to have the chart determine these value upon chart initialization like so:
//get the maximum and minimum values from the dataProvider
AmCharts.addInitHandler(function(chart) {
var maximum = Number.MIN_VALUE;
var minimum = Number.MAX_VALUE;
chart.dataProvider.forEach(function(data) {
//for each dataProvider element, check the properties that correspond to the chart graphs' valueFields.
chart.graphs.forEach(function(graph) {
if (data[graph.valueField] != null) {
maximum = Math.max(maximum, data[graph.valueField]);
minimum = Math.min(minimum, data[graph.valueField]);
}
});
});
chart.valueAxes[0].maximum = maximum;
chart.valueAxes[0].minimum = minimum;
chart.valueAxes[0].strictMinMax = true;
}, ["serial"]);
Demo

Can't get amChart to fill based on function

For a while now I'm trying to fill an amChart based on a javascript function that I've made. What I want is to set a lot of the chartproperties that don't change, as a variable, which I can use in a lot of functions that make or fill a chart. My code is:
var chartProperties = {
"theme": "light",
"type": "serial",
"startDuration": 1,
"dataProvider": [],
"rotate": false,
"categoryField": "organisatie",
"valueAxes": [ {
"gridColor": "#FFFFF",
"minimum": 0,
"gridAlpha": 0.2,
"dashLength": 0
} ],
"gridAboveGraphs": true,
"startDuration": 1,
"graphs": [ {
"balloonText": "[[category]]: <b>[[value]]</b>",
"fillColorsField": "fillcolor", //Dit veld heb ik meegegeven vanuit SQL functie en bevat de HEX kleurcodes BD
"fillAlphas": 0.8,
"lineAlpha": 0.2,
"type": "column",
"valueField": "score"
} ],
"chartCursor": {
"categoryBalloonEnabled": false,
"cursorAlpha": 0,
"zoomable": false
},
"categoryAxis": {
"gridPosition": "start",
"gridAlpha": 0,
"tickPosition": "start",
"tickLength": 20
},
"export": {
"enabled": true
}
};
var chart = AmCharts.makeChart("chartaveragescore", chartProperties);
var organization = $("#organization").val();
var indicator = $("#indicators").val();
var funcid = "fill_chart_average_score";
var dataChart = $.getJSON('functions/getfunctions.php', {
"organization":organization,
"indicator":indicator,
"funcid":funcid});
function updateOrganizationAverageScore() {
chart.dataProvider = dataChart;
chart.validateData();
}
I don't understand what I am doing wrong. Can I set the $.getJSON as a variable? Any help is much appreciated.
I already solved it myself. I looked here on Stack and discovered that I can't set a directly var = with $.getJSON and then use it later one because I'm missing the callback.
My code that works now is:
function updateOrganizationAverageScore() {
var organization = $("#organization").val();
var indicator = $("#indicators").val();
var funcid = "fill_chart_average_score";
//console.log('changed');
$.getJSON('functions/getfunctions.php', {
"organization":organization,
"indicator":indicator,
"funcid":funcid},
function(dataChart) {
var chart = AmCharts.makeChart("chartaveragescore", chartProperties);
chart.dataProvider = dataChart;
chart.validateData();
chart.startDuration = 1;
});
}

amcharts: reverse time (category) axis?

Is it possible to reverse the category axis of a time-based chart in amcharts? I know that the value axis can be easily flipped but I've not seen a solution for the category axis. I need to have the most relevant and therefore recent data on the left.
I'm using a time-based area chart. Here's a demo: http://jsfiddle.net/N5rpu/1/
In the example I've reversed the value axis and done the same to the category axis just to show that nothing happens.
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "none",
"pathToImages": "http://www.amcharts.com/lib/3/images/",
"dataProvider": chartData,
"valueAxes": [{
"position": "left",
"title": "Unique visitors",
"reversed": true
}],
"graphs": [{
"fillAlphas": 0.4,
"valueField": "visits"
}],
"chartScrollbar": {},
"chartCursor": {
"categoryBalloonDateFormat": "JJ:NN, DD MMMM",
"cursorPosition": "mouse"
},
"categoryField": "date",
"categoryAxis": {
"minPeriod": "mm",
"parseDates": true,
"reversed": true
}
});
In fact I had the opposite problem - dates in the AmCharts categoryAxis where being displayed in reverse from chronological order!
This was achieved by ordering the dates from most recent to less recent in the dataProvider array, i.e.
"dataProvider": [{
"value": 74,
"date": "2014-11-16"
},
{
"value": 73,
"date": "2014-11-15"
},
{
"value": 70,
"date": "2014-11-14"
}];

Categories