Highcharts with dynamic data $http.post angular js - javascript

$http.post(galileoServer + "actions.php", {
"action": "get-attendance-graph",
"user": window.localStorage.getItem("username")
}).success(function(result){
//console.log(result)
busyIndicator("hide");
$('#attendance-graph').highcharts({
credits: 0,
tooltip:{
enabled: false
},
chart: {
type: 'bar'
},
title: {
text: '',
style: {
display: "none"
}
},
xAxis: {
categories: ['June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb', 'Mar', 'Apr', 'May']
},
yAxis: {
min: 0,
title: {
text: 'No. of days'
},
gridLineWidth: 0,
minorGridLineWidth: 0,
labels: { //to disable points displayed
enabled: false
}
},
legend: {
reversed: true
},
plotOptions: {
series: {
stacking: 'normal',
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
formatter: function() { //function to avoid displaying zero values
if (this.y != 0) {
return this.y;
} else {
return null;
}
}
/*style: {
textShadow: '0 0 3px black, 0 0 3px black'
}*/
}
}
},
series: [{
name: 'Absent',
data: [result.absentData]
}, {
name: 'Present',
data: [result.presentData]
}]
});
}).error(function(result, status){
alert(status + "\nCouldn't connect to Galileo server due to network problem")
});
I am trying to load the data via ajax but the graph doesn't gets loaded the graph loaded is blank.
The coding snippet is provided.
I also tried with the getJSON part, but it also didn't worked.
Kindly let me know the solution, as I'm unable to get the graph since last two days.
The console output is {"absentData":"0,0,2,0,0,1,0,0,0,0,0,0","presentData":"30,31,29,30,31,29,31,31,28,31,30,31"}

Your json is not properly formed for Highcharts. You want an array of numbers, what you are giving it is an array of one element a string:
data: ["0,0,2,0,0,1,0,0,0,0,0,0"] // an array of a single string...
It's better that you fix this in your PHP code. You'll need to build a php array of ints (do not build a concatenated string) and then use json_encode.
If you can't fix it in the PHP, you could do something like:
data: $.parseJSON("["+result.absentData+"]")
but this is somewhat ugly.

Related

How to fetch json array data into highcharts in angularjs

I want to display a bar graph using highcharts.I am devoloping an app in play framework(play-java),in which I return a response from the java api which contains data in json format.It contains a field 'name' which contains data like 'Data','Gadgets','Others' etc.I want the x axis of the chart to take these values from json array which gets returned in response.
Here is the code for the response in .js
for(var i=0;i<response.data.result.length;i++)
{
$scope.total=$scope.total+parseInt(response.data.result[i].item_price);
}
var j=0;
console.log(response.data.result);
while(j<response.data.result.length)
{
$scope.jsonArray=[{
name:response.data.result[j].category_name,
y: (parseInt(response.data.result[j].item_price)/$scope.total)*100,
}]
$scope.renderChart();
}
The code for bar graph
$scope.renderChart = function()
{
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Your Expenses'
},
subtitle: {
text: 'Your total spent money is '+$scope.total+'.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Money spent in percentage'
}
},
legend: {
enabled: false
},
credits: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: [{
name: 'Categories',
colorByPoint: true,
data:$scope.jsonArray
}]
});
}
I know that I can't use the while loop in the response code mentioned.That's where i am looking help for.The y axis should calculate the percentage value .I want to generate 'names' for x axis and percentage for y axis of the chart.Thanks in advance..
All we have to do is to just initialize the jsonArray as empty before doing the looping.Add a for loop so that it iterates through the array and assigns the values appropriately.
The changed code
$scope.jsonArray = [];
for(var i=0;i<response.data.result.length;i++)
{
$scope.jsonArray[i]={
name:response.data.result[i].category_name,
y: (parseInt(response.data.result[i].item_price)/$scope.total)*100,
}
$scope.renderChart();
console.log(response.data.result[i]);
}
console.log($scope.jsonArray);
})
Anyway thanks....

How can I get the yAxis of Highcharts to display categories instead of number values?

I have this fiddle JSfiddle
Here is the reproduced code:
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
xAxis: {
categories: ['Heroku', 'Ruby','Lisp','Javascript','Python','PHP']
},
yAxis: {
categories: ['low','medium','high'],
title: {
text: 'expertise',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ' millions'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
series: [{
data: ['low','high','low','medium','medium']
}]
});
});
If you look at the fiddle the yAxis does not render and has a value of for every x category. I've been looking at the highcharts api, but I can't seem to get this right. The code makes sense to me but I'm obviously doing something wrong. Can someone point out why the YAxis is not displaying correctly?
As mentioned in my comment, you need to supply the numeric value of the category, not the category name.
In the case of categories, the numeric value is the array index.
Also, in your case, the way you are trying to plot the values, I would add an empty category at the beginning, otherwise your first category of low gets plotted as 0, which doesn't seem right.
So,
categories: ['low','medium','high']
Becomes
categories: ['','low','medium','high'],
And
data: ['low','high','low','medium','medium']
Becomes
data: [1,3,1,2,2]
Updated fiddle:
http://jsfiddle.net/jlbriggs/k64boexd/3/
Check this fiddle:
http://jsfiddle.net/navjot227/k64boexd/2/
Trick is to utilize the formatter function. You can use a similar formatter function on y-axis labels too if that's desired. Though it seems like you need it for data labels for this problem.
$(function() {
$('#container').highcharts({
chart: {
type: 'bar'
},
xAxis: {
categories: ['Heroku', 'Ruby', 'Lisp', 'Javascript', 'Python', 'PHP']
},
yAxis: {
title: {
text: 'expertise',
align: 'high'
},
labels: {
overflow: 'justify',
}
},
tooltip: {
valueSuffix: ' millions'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true,
formatter: function() {
if (this.y == 0) {
return 'low'
} else if (this.y == 1) {
return 'medium'
} else {
console.log(this.y);
return 'high'
}
}
}
}
},
series: [{
data: [0, 2, 0, 1, 1]
}]
});
});
In my opinion, it is kinda unlikely for a line graph to have a y-axis category, since it speaks more of amount or value. In your case, "low, medium, and high" speaks of ranges, with which a certain value can be assigned to any of it.
Thus, Highcharts accepts series data in numeric form. But you can work around it by setting ['low', 'medium', 'high'] in the category attribute of yAxis, then setting series data as an array of number corresponding to the index of the category, i.e. [0,1,1,2,...] and tweaking the tooltip to display the category instead of the y value using formatter attribute.
Here is the code:
$(function() {
yCategories = ['low', 'medium', 'high'];
$('#container').highcharts({
title: {
text: 'Chart with category axes'
},
xAxis: {
categories: ['Heroku', 'Ruby','Lisp','Javascript','Python','PHP']
},
yAxis: {
categories: yCategories
},
tooltip: {
formatter: function() {
return this.point.category + ': ' + yCategories[this.y];
}
},
series: [{
data: [0, 1, 2, 2, 1]
}]
});
});
Here is a working example : JSFiddle

Highcharts data csv load

i'm having trouble displaying chart from my csv file.it doesn't plot chart. maybe my parser it is the problem. firebug says no major errors but i'm stuck i dont know how to make it work. please help..
this is how my csv looks like:
1437931522,30
1437931555,30.25
1437931768,30.25
1437931785,29.75
1437931802,30.25
1437932702,30.5
1437933601,29.75
1437933974,30
end of file is \n, but seems to not showing right here so I inserted extra enter
this is the code:
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: true
}
});
var mydata = [];
var times = [];
$.get('data.csv', function(data) {
// Split the lines
var lines = data.split('\n');
// Iterate over the lines and add categories or series
$.each(lines, function(lineNo, line) {
var items = line.split(',');
if(lineNo=>0)
{
times.push(new Date(items[0]*1000).toUTCString());
mydata.push(items[1])
}
});
});
$('#container').highcharts({
title: {
text: 'Temperature',
x: -20 //center
},
subtitle: {
text: 'test1',
x: -20
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%b %e, %Y',
year: '%Y'
},
categories: times
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Temp',
data: mydata
}]
});
});``
is it ok, to get csv just with 'data.csv' if it is in the same directory or I have to set entire url?
this ismy fiddle:
http://jsfiddle.net/skoky2/yw25z6ow/1/
You should use the following code in your main module
data: {
csv: csv
},
Ref: data-module
1) If you use datetime type of xAxis, you should no use categories. You can define tickPositions
2) Point value should be number not string, so replace:
mydata.push(items[1])
with
mydata.push(parseFloat(items[1]))
i managed to get it work. but I noticed that this chart works only in IE 8, not in firefox or chrome. firefox with ie tab aslo works

how to create a column char with highcharts where each column has a different color

I´ve a chart using highcharts, the only problem is that each column has the same column.
What should I do so each column has a different column.
Here is my code:
var charts = [];
$containers = $('#container1');
var datasets = [
{
name: 'Tokyo',
data: [49, 57]
}];
var cat = ['A', 'B'];
console.log(datasets);
$.each(datasets, function(i, dataset) {
console.log(dataset);
charts.push(new Highcharts.Chart({
chart: {
renderTo: $containers[i],
type: 'column',
marginLeft: i === 0 ? 100 : 10
},
title: {
text: dataset.name,
align: 'left',
x: i === 0 ? 90 : 0
},
credits: {
enabled: false
},
xAxis: {
categories: cat,
labels: {
enabled: i === 0
}
},
yAxis: {
allowDecimals: false,
title: {
text: null
}
},
legend: {
enabled: false
},
series: [dataset]
}));
});
Thanks in advance.
To have each column be a different color, all you have to do is set the colorByPoint property to true.
Reference:
http://api.highcharts.com/highcharts#plotOptions.column.colorByPoint
Alternatively you can make each column a separate series, which gives you additional levels of control.
OTOH, in the majority of cases, having each column a separate color serves no purpose except to clutter and confuse the data, and make the user work harder cognitively to interpret the chart.
If you want to highlight a single column for a particular reason, you can do that by adding the fillColor property to the data array:
Something like:
data:[2,4,5,{y:9,fillColor:'rgba(204,0,0,.75)',note:'Wow, look at this one'},4,5,6]
I finally found a way to show more than 1 color for each column:
var charts1 = [];
var $containers1 = $('#container1');
var datasets1 = [{
name: 'Dalias',
data: [29]
},
{
name: 'Lilas',
data: [1]
},
{
name: 'Tulipanes',
data: [15]
}];
$('#container1').highcharts({
chart: {
type: 'column',
backgroundColor: 'transparent'
},
title: {
text: 'Montos pedidos por división'
},
tooltip: {
pointFormat: '<span style="color:{series.color};" />{series.name} </span>:<b>{point.y}</b>',
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
},
series : {
cursor: 'pointer',
point: {
events: {
/*click: function() {
verDetalle("Especialidades,"+ this.series.name);
}*/
}
}
}
},
credits:{
enabled: false
},
yAxis: {
min: 0,
title: {
text: ''
}
},
xAxis: {
categories: ['División']
},
series: datasets1
});

Displaying array values in Bar chart of HighCharts

I am trying to display values which I am getting dynamically. In the below code I am trying to store the values in array and I am trying to use the array values in "series: data".
Nothing is getting displayed in the graph.
I know this is very simple question but I did not get any satisfactory answer when I googled it. Please help
var x = window.location.search.replace( "?", "" );
x = x.substring(3);
var array = x.split(","); // I am storing my dynamic values in this array
$(function () {
//alert(array); ----- I am able to see the values here
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Wireless Experience Meter'
},
subtitle: {
text: 'Sub - Time to Download'
},
xAxis: {
categories: ['Text'],
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Time (ms)',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ' ms'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -40,
y: 100,
floating: true,
borderWidth: 1,
backgroundColor: '#FFFFFF',
shadow: true
},
credits: {
enabled: false
},
series: [{
name: 'Attempt 1',
//data: [635, 203, 200]
data : [array[0]] // I need to pass the variables here to get it displayed
}, {
name: 'Attempt 2',
//data: [133, 408, 698]
data : [array[1]]
}, {
name: 'Attempt 3',
//data: [973, 914, 4054]
data : [array[2]]
}]
});
});
You don't tell us what the variable array equals but since its generated from x.split(","), it's elements are going to be strings and not the numeric values Highcharts needs.
So convert it with parseInt or parseFloat:
var numericData = [];
for (var i = 0; i < array.length; i++){
numericData.push(parseFloat(array[i]));
}
...
series: [{
name: 'Attempt 1',
data : numericData
},
...
[array[0]] is not an array, that looks like console output not javascript. But [[0]] or [0] technically would be. However, since a call to array (array(0)) generates an array then I think you want data: array(0).
Outside shot at data : [array(0)] if you didn't show the example data correctly. I've never used HighCharts so I don't know what it's expected but I still go with data : array(0)

Categories

Resources