MongoDB & AMCharts - javascript

I am trying to create an AMchart with some values from my mongoDB using mongoose and Node.js. Since Node.js is asynchronous I can't pass my values from the query to the chart, If I put the chart creation inside the same function scope as the query when I do the calling in the handlebars I get nothing since the chart creation is inside the query, but this is the onñy way I have been able to retrieve the data. My code is as follows:
<script>
var Edad = require('../models/edad');
var data = [];
Edad.find().lean().exec(function(err, docs) {
if (err) throw err;
data = docs;
for (var i in data) {
delete data[i]._id;
delete data[i].__v;
}
});
var chart = AmCharts.makeChart( "chartdiv", {
"type": "serial",
"theme": "patterns",
"dataProvider": data,
"valueAxes": [ {
"gridColor": "#FFFFFF",
"gridAlpha": 0.2,
"dashLength": 0
} ],
"gridAboveGraphs": true,
"startDuration": 1,
"graphs": [ {
"balloonText": "Edad: [[category]]: <b> Numero Vacunas: [[value]]</b>",
"fillAlphas": 0.8,
"lineAlpha": 0.2,
"type": "column",
"valueField": "vacunas"
} ],
"chartCursor": {
"categoryBalloonEnabled": false,
"cursorAlpha": 0,
"zoomable": false
},
"categoryField": "edad",
"categoryAxis": {
"gridPosition": "start",
"gridAlpha": 0,
"tickPosition": "start",
"tickLength": 20
},
"export": {
"enabled": true
}
} );
</script>
<div id="main-wrapper">
<div class="container">
<article class="box post">
<header>
<h2>Vacunas Por Edad</h2>
<p>Estadisticas para el numero de vacunas aplicadas por cada grupo de edad de los pacientes</p>
</header>
<div id="chartdiv"></div>
</article>
</div>
</div>
I Need the data from the JSON "data" to be the value for "data provider" in the chart creation, any help would be much appreciated

You could try to build the chart and then add the data later using validateNow:
<script>
var chart = AmCharts.makeChart( "chartdiv", {
"type": "serial",
"theme": "patterns",
"dataProvider": [],
"valueAxes": [ {
"gridColor": "#FFFFFF",
"gridAlpha": 0.2,
"dashLength": 0
} ],
"gridAboveGraphs": true,
"startDuration": 1,
"graphs": [ {
"balloonText": "Edad: [[category]]: <b> Numero Vacunas: [[value]]</b>",
"fillAlphas": 0.8,
"lineAlpha": 0.2,
"type": "column",
"valueField": "vacunas"
} ],
"chartCursor": {
"categoryBalloonEnabled": false,
"cursorAlpha": 0,
"zoomable": false
},
"categoryField": "edad",
"categoryAxis": {
"gridPosition": "start",
"gridAlpha": 0,
"tickPosition": "start",
"tickLength": 20
},
"export": {
"enabled": true
}
} );
var Edad = require('../models/edad');
Edad.find().lean().exec(function(err, data) {
if (err) throw err;
for (var i in data) {
delete data[i]._id;
delete data[i].__v;
}
chart.validateNow(data, false);
});
</script>

Related

Initial date range using amchart's gantt

I am using Amchart's Gantt chart.
The segments are divided by dates.
I need the chart's navigator initial location will be between two dates, and not to be applied all over the chart.
the current behavior:
The expected result:
I tried adding 'startDate' and 'endDate' but without success.
my Amchat;s configurations:
<AmCharts.React
className="my-class"
style={{
width: '50%',
height: '250px'
}}
options={
{
"height": "500",
"hideCredits":true,
"type": "gantt",
"theme": "light",
"marginRight": 70,
"period": "DD",
"dataDateFormat": "YYYY-MM-DD",
"columnWidth": 0.45,
"valueAxis": {
"type": "date"
},
"graph": {
"lineAlpha": 1,
"lineColor": "#fff",
"fillAlphas": 0.85,
"showAllValueLabels": false,
"cornerRadiusTop": 4
},
"rotate": true,
"categoryField": "category",
"segmentsField": "segments",
"colorField": "color",
"startDateField": "start",
"endDateField": "end",
"dataProvider": this.state.dataProvider,
"valueScrollbar": {
"selectedBackgroundColor": '#f3faff',
"selectedBackgroundAlpha": 1,
"autoGridCount": false
},
"chartCursor": {
"cursorColor": "#55bb76",
"valueBalloonsEnabled": false,
"cursorAlpha": 0,
"valueLineAlpha": 0.5,
"valueLineBalloonEnabled": false,
"valueLineEnabled": false,
"zoomable": false,
"valueZoomable": true
},
"export": {
"enabled": false
}
}
}
/>
Thanks.
You can use "zoomToDates(start, end)" property of AmGanttChart. Here is the relevant reference:
AmGanttChart | JavaScript Charts v. 3 | amCharts
Also you can find the usage of the property from that question:
AM Charts initial view using zoomToDates

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

Retrieving data to show in amcharts

I'm trying to show data in a chart, this time, using amchart and angular to consume REST Service.
this is the code to consume service and call amchart:
function GetData($scope, $http){
$http.get('http://localhost/api/v1/index.php/data').
success(function(data){
//$scope.dados = data;
var json = data;
var chart = AmCharts.makeChart( "chartdiv", {
"type": "serial",
"theme": "light",
"dataProvider": data,
"valueAxes": [ {
"gridColor": "#FFFFFF",
"gridAlpha": 0.2,
"dashLength": 0
} ],
"gridAboveGraphs": true,
"startDuration": 1,
"graphs": [ {
"balloonText": "[[category]]: <b>[[value]]</b>",
"fillAlphas": 0.8,
"lineAlpha": 0.2,
"type": "column",
"valueField": "visits"
} ],
"chartCursor": {
"categoryBalloonEnabled": false,
"cursorAlpha": 0,
"zoomable": false
},
"categoryField": "country",
"categoryAxis": {
"gridPosition": "start",
"gridAlpha": 0,
"tickPosition": "start",
"tickLength": 20
},
"export": {
"enabled": true
}
} );
});
}
this is my html
<body ng-controller="GetData">
<div id="chartdiv" style="width: 100%; height: 500px"></div>
</body>
It is not showing anything
Do you have a completely blank output in your browser? if so check for javascript errors in your browser. this should point you in the right direction.
are you including the amcharts libraries somewhere? I cannot see this in your html or js.
if you are seeing a blank chart, then it is likely that there is a problem with your json, check or post here for help with that.

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;
});
}

How to add labels to pie charts in amCharts?

The following is the function used to generate a pie chart. Everything is working fine, except for the addLabel parameter.
graphSentiChart:function(graphData) {
if(graphData.length < 1){
$('.dataContentStatsPie').html('No data available')
}
// $(".dataContentAllPie").empty();
var piechart = AmCharts.makeChart("chartPie", {
"type": "pie",
"theme": "light",
"autoMargins": true,
"marginTop": 0,
"marginBottom": 10,
"marginLeft": 0,
"marginRight": 0,
"dataProvider": graphData,
"titleField":"key",
"valueField": "value",
"addLabel": (0, 25, 'Total Tweets= 360'),
"startDuration":0,
"responsive": {
"enabled":true
},
"legend":{
"autoMargins":false,
"marginLeft":20,
"enabled": true,
"spacing":20,
"markerType":"circle",
"horizontalGap" :20,
},
"labelsEnabled":false,
//"balloonText": "[[title]]<br><span style='font-size:14px'><b>[[value]]</b> ([[percents]]%)</span>",
"colorField": "color",
"innerRadius": "60%",
"export": {
"enabled": true,
"libs": {
"path": "http://amcharts.com/lib/3/plugins/export/libs/"
}
}
});
What I have given in the addLabel parameter is not being taken and the label is also not getting shown. Can anybody help me on this?
There is no such property in amCharts addLabel. There is a method, which can be used to add labels to an already existing chart object.
To specify labels in the JSON config of the chart, use allLabels:
"allLabels": [{
"x": 0,
"y": 25,
"text": "Total Tweets= 360"
}]

Categories