Cannot get data to display on chart - javascript

I am receiving data correctly in my console from the mtgox api. However, I cannot get the data to display on my chart. I'm using highcharts. Any help is appreciated. My code is posted below. Thanks.
Javascript code:
$(document).ready(function() {
$.ajax({
url: "/chart/ajax_get_chart", // the URL of the controller action method
dataType: "json",
type: "GET",
success: function(result) {
var result = JSON.parse(result);
var date = new Array();
var price = new Array();
for (var i = 0; i < result.length; i++) {
date.push(result[i]['date']);
price.push(result[i]['price']);
}
$(function () {
console.log(date);
$('#container').highcharts({
chart: {
type: 'line',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'Bitcoin Price',
x: -20 //center
},
subtitle: {
text: 'Source: MtGox.com',
x: -20
},
xAxis: {
categories: 'datetime'
},
yAxis: {
title: {
text: 'Price'
},
plotLines: [{
value: 'Price',
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: [{
name: 'Bitcoin',
data: price
}]
});
});
}
});
});
Model:
public function ajax_get_chart() {
$quotes = $this->rest->get('api/1/BTCUSD/trades/fetch');
$series_data = array();
$results = $quotes->return;
foreach ($results as $quote)
{
$series_tmp = array(
'date' => $quote->date,
'price' => $quote->price
);
$series_data[] = $series_tmp;
}
return json_encode($series_data);
}
}

Try changing this:
$('#container').highcharts({
chart: {
type: 'line',
marginRight: 130,
marginBottom: 25
},
to this:
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
type: 'line',
marginRight: 130,
marginBottom: 25
},

Related

How to show multiple graphs in drilldown (highcharts)?

NET MVC Project, where I use Highcharts. In my charts i have columns and a spline.
I have already implemented drilldown for my chart and it works perfectly, but only for the columns. On the first level the columns and the spline is shown, but when I trigger drilldown only the columns are shown. data2 should be the spline.
var mychart = Highcharts.chart('container', {
chart: {
zoomType: 'xy',
spacingBottom: 40,
spacingTop: 40,
events: {
// DRILLDOWN
drilldown: function (e) {
//Some variables id, func
$.getJSON(`/Home/GetDataForMinuteDrilldown?id=${id}&function=${func}`, function (data) {
console.log(data);
var durationArrMinutes = data.map(function (item) {
return item['minuteavg'];
});
var errorArrayMinutes = data.map(function (item) {
return item['errorsperminute']
});
var minuteArray = data.map(function (item) {
return {
name: drill + ":" + item['minute'],
y: item['minuteavg'],
drilldown: item['minute']
};
});
data2 = {
name: 'Errors per Minute',
type: 'spline',
data: errorArrayMinutes,
tooltip: {
valueSuffix: ' '
}
}
data = {
name: 'Average Duration per Minute',
type: 'column',
yAxis: 1,
data: minuteArray,
tooltip: {
valueSuffix: ' ms'
},
data2 //I think this is the error, but I i know no solution
}
console.log('Data:')
console.log(data);
mychart.hideLoading();
mychart.addSeriesAsDrilldown(e.point, data);
});
}
}
},
title: {
text: 'Performance and Error Analytics'
},
subtitle: {
text: 'Analytics of: ' + func
},
xAxis: [{
type: 'category',
crosshair: true
}],
yAxis: [{ // Primary yAxis
labels: {
format: '{value}',
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'Errors',
style: {
color: Highcharts.getOptions().colors[2]
}
}
}, { // Secondary yAxis
title: {
text: 'Duration in ms',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} ms',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'center',
x: 0,
verticalAlign: 'bottom',
y: 50,
floating: true,
backgroundColor:
Highcharts.defaultOptions.legend.backgroundColor || // theme
'rgba(255,255,255,0.25)'
},
series: [{
name: 'Average Duration per Hour',
type: 'column',
yAxis: 1,
data: durationPerHourArray,
tooltip: {
valueSuffix: ' ms'
}
}, {
name: 'Errors',
type: 'spline',
data: errorArray,
tooltip: {
valueSuffix: ' '
}
}],
drilldown: {
activeAxisLabelStyle: {
textDecoration: 'none',
fontStyle: 'normal',
color: 'black'
},
series: []
}
});
The addSeriesAsDrilldown method allows to add only one series to drilldown. From source code:
Chart.prototype.addSeriesAsDrilldown = function (point, options) {
this.addSingleSeriesAsDrilldown(point, options);
this.applyDrilldown();
};
Instad of addSeriesAsDrilldown, you can use internal addSingleSeriesAsDrilldown method to add both series and call applyDrilldown:
mychart.addSingleSeriesAsDrilldown(e.point, data);
mychart.addSingleSeriesAsDrilldown(e.point, data2);
mychart.applyDrilldown();
Live demo: http://jsfiddle.net/BlackLabel/obukspae/
Source code: https://code.highcharts.com/modules/drilldown.src.js

Real Time Bar chart using Highcharts and AngularJs

Using a Highcharts example (here), I have loaded a bar chart in AngularJs.
HTML code below:
<!DOCTYPE html>
<html ng-lang="en" ng-app="myModule">
<head>
<meta charset="ISO-8859-1">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/highcharts/6.0.7/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<title>Insert title here</title>
</head>
<script>
angular.module('myModule',[])
.controller('myController',function($q, $scope, $http){
$scope.cnt = 1;
var t = 0;
setInterval(function(cnt){
fetchData($scope.cnt).then(function(success){
$scope.chartOptions={
chart: {
type: 'bar',
events:{
load:function(){
var rowClass = this.series[0];
console.log("rowClass : "+rowClass);
}
}
},
title: {
text: 'ClassNames By Count Chart'
},
subtitle: {
text: 'Admin Chart'
},
xAxis: {
categories: $scope.rows,
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Population (millions)',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ' millions'
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -40,
y: 80,
floating: true,
borderWidth: 1,
backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
shadow: true
},
credits: {
enabled: false
},
series: [{
name: 'Year 1800',
data: (function(){
var data = [];
var i;
console.log("In Series function() : $scope.num : "+$scope.num ); //Update is being done propertly
for(i=1;i<4;i=i+1){
data.push($scope.num[i]);
}
return data;
}())
}, {
name: 'Year 1900',
data: [133, 156, 947, 408, 6]
}, {
name: 'Year 2000',
data: [814, 841, 3714, 727, 31]
}, {
name: 'Year 2016',
data: [1216, 1001, 4436, 738, 40]
}]
};
if(t==0){
t = t+1;
Highcharts.chart('container',$scope.chartOptions);
}
},function(error){
console.log("in error functio : "+error);
});
},2000);
var cnt = 0;
var str = "str";
setInterval(function(){
str = str+cnt;
cnt++;
$http({
method: "GET",
url : "http://localhost:8080/hello/"+str+"/3"
}).then(function success(data){
}, function error(data){
console.log("error "+data.data);
});
},5000);
var fetchData = function(cnt){
$scope.cnt = $scope.cnt+1;
var deferred = $q.defer();
$http({
method : "GET",
url : "http://localhost:8080/hello"
}).then(function mySuccess(response) {
$scope.myRes = response.data;
$scope.rows = $scope.myRes;
var i;
$scope.num = [];
for(i=0;i<4;i=i+1){
$scope.num.push(++cnt*110);
}
deferred.resolve();
}, function myError(response) {
console.log("error");
$scope.myRes = response;
deferred.reject();
});
return deferred.promise;
};
});
</script>
<body ng-controller="myController">
<hcbar options="chartOptions"></hcbar>
<div id="container"></div>
</body>
</html>
Now I require to load the bar counts in the chart to be loaded dynamically that is as the count is updated in Database the new values have to be reflected in the chart (Real Time Data)
You will see I ahve written the data : function in my file which updates the data array in a loop:
series: [{
name: 'Year 1800',
data: (function(){
var data = [];
var i;
console.log("In Series function() : $scope.num : "+$scope.num ); //Update is being done propertly
for(i=1;i<4;i=i+1){
da.push($scope.num[i]);
}
returndata;
}())
},
The updated values are correctly printed in console but are NOT BEING REFLECTED IN THE CHART BAR!
I know there is this function addPoint() which adds a point to the array. But here I do not want a new Object in the series array but the updated values in the series[0].data array!
How can this be accomplished?
If you put your values in $scope and use like following.
series: [{
data: [
{ name: 'Year 1800', y: $scope.num1, color: 'red' },
{ name: 'Year 1900', y: $scope.num2, color: 'green' },
{ name: 'Year 2000', y: $scope.num3, color: 'blue' },
{ name: 'Year 2016', y: $scope.num4, color: 'yellow' }
]
}],
when you will update $scope.num1, it will definitely update in chart.
here is a WORKING Example.
$scope.chartOptions = {
chart: {
type: 'column',
spacingLeft: 0,
spacingRight: 0,
height: 300
},
title: {
text: ''
},
xAxis: {
categories: ['1800', '1900', '2000', 2016'],
crosshair: true
},
yAxis: {
min: 0,
tickInterval: 20,
title: {
text: ''
},
labels:
{
enabled: false
}
},
legend: {
enabled: false
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
credits: {
enabled: false
},
series: [{
data: [
{ name: 'Year 1800', y: $scope.num1, color: 'red' },
{ name: 'Year 1900', y: $scope.num2, color: 'green' },
{ name: 'Year 2000', y: $scope.num3, color: 'blue' },
{ name: 'Year 2016', y: $scope.num4, color: 'yellow' }
]
}]
};

howto handle objects asp.net javascript highcharts

I'm trying to create a chart with values from my database.
On the server side I throw the values in a list and pass the list to the client.
But somehow the chart just won't display anything at all.
Here's my javascript code:
$(document).ready(function () {
$("#but").click(function (e) {
getData();
});
});
function CreateTempChart(options) {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chart',
type: 'line',
marginRight: 25,
marginBottom: 25,
zoomType: 'xy'
},
title: {
text: 'Temperature',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'datetime',
categories: []
},
yAxis: {
title: {
text: 'in °C'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.options.name + '</b><br/>' +
this.x + ': ' + this.y;
}
},
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'top',
x: -50,
y: 40,
borderWidth: 0
},
series:[]
});
chart.addSeries(options);
};
function getData() {
$.ajax({
url: "BasicLine",
dataType: 'json',
type: "POST",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function(result) {
var yo = JSON.parse(result);
var arr = [];
$.map(yo, function (item) {
var t = item.Time.replace("\/Date(", "").replace(")\/", "");
var obj = {
name: "Temperature",
data: item.Value,
categories: t
};
arr.push(obj);
});
var jsonArray = JSON.stringify(arr);
console.log(jsonArray);
CreateTempChart(jsonArray);
},
error: function () {
alert("oh no");
}
});
}
The log looks like this
[{"name":"Temperature","data":10.7,"categories":"1430408770000"},{"name":"Temperature","data":10.8,"categories":"1430408990000"},....]
Any ideas? I'm not quite familiar with js.

HighCharts with Series datet/time

[{"name":"M3","data":[["2014-04-16 23:03:59","0"],["2014-04-15 17:48:37","0"],["2014-04-15 17:43:16","1"],["2014-04-15 17:42:52","0"],["2014-04-15 17:36:19","1"],["2014-04-15 17:35:43","0"],["2014-04-15 17:35:31","0"],["2014-04-15 17:30:22","0"],["2014-04-15 17:27:47","1"],["2014-04-15 17:26:00","1"],["2014-04-15 17:19:28","1"],["2014-04-15 17:00:26","0"],["2014-04-15 16:53:18","0"]]},{"name":"M2","data":[["2014-04-16 23:03:47","0"],["2014-04-15 17:47:25","0"],["2014-04-15 17:33:20","1"],["2014-04-15 17:30:10","0"],["2014-04-15 16:57:51","0"]]},{"name":"M1","data":[["2014-04-15 17:47:37","0"],["2014-04-15 17:45:15","0"]]}]
The above is the JSON data for HighCHarts wherein I need to set the X axis to date/time and Y to status . The JSON is generated and attached to the series property and is used as below: This is not plotting at all.
var handlerURL = "http://localhost:50687/Handler.ashx?";
$.ajax({
url: handlerURL,
type: "GET",
datatype: "json",
contentType: 'application/json',
complete: function (json) {
jsonData = json.responseText; alert(jsonData);
}
});
options = {
chart: {
renderTo: 'container',
type: 'spline',
marginRight: 130,
marginBottom: 50
},
setOptions: ({
global: { useUTC: true }
}),
title: {
text: 'Live Data',
x: -20
},
subtitle: {
text: '',
x: -30
},
xAxis: {
type: 'datetime',
tickPixelInterval: 100,
plotLines: [{
width: 5,
color: '#808080'
}]
},
yAxis: {
min: 0, max: 1,
title: {
text: 'Status'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
this.x + ': ' + this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: []
}
options.series = jsonData;
chart = new Highcharts.Chart(options);
});

Pass Ajax data in highcharts Combination chart

I'm trying to pass the data(line data and pie_data) in a combination chart. I'm able to pass the pie_data but unable to pass the line data. Here is my jsFiddle Link
Please suggest where I'm going wrong?
Here is my code.
$(function () {
var line_data = [{ // this is AJAX returned line_data.
'data': [
[1383741000000, 1608.3000000000002],
[1383741900000, 1611.9999999999973],
[1383742800000, 1612.299999999997]
],
'name': 'Bangalore'
}, {
'data': [
[1383741000000, 54.2],
[1383741900000, 54.300000000000004],
[1383742800000, 54.300000000000004]
],
'name': 'New Delhi'
}];
// this is AJAX returned pie_data.
// I'm able to get the pie chart, but not the line chart.
var pie_data = [['Jane',13], ['Jnanae',33] , ['Jasvdwdne',113]];
$('#container').highcharts({
chart: {
},
title: {
text: 'Combination chart'
},
xAxis: {
type: 'datetime'
},
series: [{
type: 'spline',
name: 'Average',
data: line_data,
marker: {
lineWidth: 2,
lineColor: Highcharts.getOptions().colors[3],
fillColor: 'white'
}
}, {
type: 'pie',
name: 'Total consumption',
data: pie_data,
center: [100, 80],
size: 100,
showInLegend: false,
dataLabels: {
enabled: false
}
}]
});
});
Try this out:- http://jsfiddle.net/5yzb2/6/
JS:-
$(function () {
var seriesOptions = [];
var line_data = [{ // this is AJAX returned line_data.
data: [
[1383741000000, 1608.3000000000002],
[1383741900000, 1611.9999999999973],
[1383742800000, 1612.299999999997]
],
name: 'Bangalore'
}, {
data: [
[1383741000000, 54.2],
[1383741900000, 54.300000000000004],
[1383742800000, 54.300000000000004]
],
name: 'New Delhi'
}];
// this is AJAX returned pie_data.
// I'm able to get the pie chart, but not the line chart.
var pie_data = [
['Jane', 13],
['Jnanae', 33],
['Jasvdwdne', 113]
];
//Adding all data seriesOptions
$.each(line_data, function (i, name) {
seriesOptions[i] = {
type: 'spline',
name: this.name,
data: this.data
};
});
seriesOptions[seriesOptions.length] = {
type: 'pie',
name: 'Total consumption',
data: pie_data,
center: [100, 80],
size: 100,
showInLegend: false,
dataLabels: {
enabled: false
}
};
$('#container').highcharts({
chart: {},
title: {
text: 'Combination chart'
},
xAxis: {
type: 'datetime'
},
tooltip: {
formatter: function () {
var s;
if (this.point.name) { // the pie chart
s = '' + this.point.name + ': ' + this.y + ' fruits';
} else {
s = '' + this.x + ': ' + this.y;
}
return s;
}
},
labels: {
items: [{
html: 'Total fruit consumption',
style: {
left: '40px',
top: '8px',
color: 'black'
}
}]
},
series: seriesOptions
});
});

Categories

Resources