using JSON dates with Highstock chart (asp.net MVC) - asp.net-mvc

I am trying to output JSON data on to Highstock chart. Initially I struggled with the JSON formatted date which I resolved by following instruction on other answer on stackoverflow by re-formatting dates. But I'm still unable to get the graph plotted on view page -
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var mydata =[];
chartOjb = new Object();
$.ajax({
type: "GET",
url: "/ReportIntance/DummyCall/2",
data: '{ }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function (index, item) {
chartOjb.name = new Date(parseInt(item.DayDate.replace("/Date(", "").replace(")/", ""), 10));
chartOjb.data = item.Series1;
mydata.push({
x: new Date(parseInt(item.DayDate.replace("/Date(", "").replace(")/", ""), 10)),
y: item.Series1
});
})
},
failure: function (response) {
alert(response);
}
});
chart1 = new Highcharts.Chart({
chart: {
renderTo: 'Chart1'
},
title: {
text: 'Delivery Price example using Chart'
},
xAxis: {
type: 'datetime'
},
yAxis: {
title: {
text: 'Price'
}
},
series: [ { data: mydata }]
});
});
</script>
<div id="Chart1" style="height: 500px; min-width: 500px"></div>
My JSON string is -
[{"DayDate":"\/Date(1334704500000)\/","Series1":4.01,"Series2":0,"Series3":0,"Series4":0,"Series5":0},
{"DayDate":"\/Date(1334705400000)\/","Series1":5.01,"Series2":0,"Series3":0,"Series4":0,"Series5":0},
{"DayDate":"\/Date(1334706300000)\/","Series1":4.51,"Series2":0,"Series3":0,"Series4":0,"Series5":0},
{"DayDate":"\/Date(1334707200000)\/","Series1":6.01,"Series2":0,"Series3":0,"Series4":0,"Series5":0},
{"DayDate":"\/Date(1334708100000)\/","Series1":4.71,"Series2":0,"Series3":0,"Series4":0,"Series5":0},
{"DayDate":"\/Date(1334709000000)\/","Series1":7.01,"Series2":0,"Series3":0,"Series4":0,"Series5":0},
{"DayDate":"\/Date(1334709900000)\/","Series1":7.01,"Series2":0,"Series3":0,"Series4":0,"Series5":0}]
Currently I'm trying to output simple line chart and using only DayDate (X-axis) and 'Series1' as Y-axis.
Highstock chart shows just 'x axis' but no line graph or y axis is shown.
Can someone point me what I'm doing wrong? Any help will be appreciated.
Edit:
After setting turboThresold field I can now see the X Axis on my highstock chart. However values from y axis are still missing.
This is how graph looks without any y axis lines. The data seems to be correct
Here's my updated code -
$(function () {
var mydata = [];
chartOjb = new Object();
// See source code from the JSONP handler at https://github.com/highslide-software/highcharts.com/blob/master/samples/data/from-sql.php
$.getJSON('/ReportIntance/DummyCall/2', function (data) {
// Add a null value for the end date
//data = [].concat(data, [[Date.UTC(2013, 9, 14, 19, 59), null, null, null, null]]);
$.each(data, function (index, item) {
chartOjb.name = new Date(parseInt(item.DayDate.replace("/Date(", "").replace(")/", ""), 10));
chartOjb.data = item.Series1;
mydata.push({ x: chartOjb.name, y: parseFloat(chartOjb.data) });
//alert(chartOjb.name + "/" + chartOjb.data);
});
// create the chart
$('#container').highcharts('StockChart', {
chart: {
//type: 'candlestick',
zoomType: 'x'
},
navigator: {
adaptToUpdatedData: false,
series: {
data: mydata
}
},
scrollbar: {
liveRedraw: false
},
title: {
text: 'Historical prices from June 2012'
},
subtitle: {
text: 'Displaying 20K records using Highcharts Stock by using JSON'
},
plotOptions: {
line: {
turboThreshold: 20450
}
},
xAxis: {
type: 'datetime',
title: 'Time',
minRange: 3600 * 1000/15 // one hour
},
yAxis:{
title: {
text: 'Prices',
style: {
color: '#89A54E'
}
},
lineWidth: 1,
opposite: false,
showEmpty: false //hides empty data series
},
series: [{
data: data,
pointStart: Date.UTC(2012, 6, 1), // first of June
pointInterval: 3600 * 1000/15,
dataGrouping: {
enabled: false
}
}]
});
});
});

Thanks to Sebastian, I can now see the graphs. Only issue I had was that I wasn't pointing to correct 'data' Your suggestion to not convert to datetime improved the performance

Related

Highcharts dynamic data from an Api

I want to create a chart that reads its data from an Api. To do that i have this fiddle http://jsfiddle.net/68oe1oLf/69/
Note: https://jsfiddle.net/68oe1oLf/69/ will lead to mixed content error and will fail to load data from the api
This is the javascript code
$(document).ready(function () {
$.get( "http://firmbridgecapital.com/live.php", function( dt ) {
localStorage.setItem("data", dt);
});
window.setInterval(function(){
$.get( "http://firmbridgecapital.com/live.php", function( dt ) {
localStorage.setItem("data", dt);
});
}, 5000);
Highcharts.setOptions({
global: {
useUTC: false
}
});
Highcharts.chart('container', {
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = parseInt(localStorage.getItem("data"));
series.addPoint([x, y], true, true);
}, 5000);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
max: 3,
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -150; i <= 0; i += 25) {
data.push({
x: time,
y: parseInt(localStorage.getItem("data"))
});
}
return data;
}())
}]
});
});
I borrowed the idea from this docs example http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/dynamic-update/
My chart is always grounded on value 1 and does not show the changing values in the y axis. How may i fix this?.
The value you are referencing, i.e. live php page, seems to be 1.x and increasing very slowly. (1.7 while I was looking).
In your parsing you do the following:
y = parseInt(localStorage.getItem("data"));
And since the value is 1.7, and you try to parse it as an integer with parseInt, it gets converted to 1. Using parseFloat will give you a slowly increasing graph.

Function to create Highcharts where the series has the correct prototype

I am attempting to write a function to add a highchart to a page and a function that can update the data for that chart based on a streaming API. I added a setInterval to simulate the streaming api.
The issue occurs on line 80. I believe it is because I have not set the series array with the chart object properly. When I need to add new data via 'addPoint', the prototype is not there. What am I missing in my AddChart function that wires the series up to highcharts?
FIDDLE:
http://jsfiddle.net/puto3Lg0/2/
$(function () {
$(document).ready(function () {
var metrics = [];
Highcharts.setOptions({
global: {
useUTC: false
}
});
function AddChart(metric) {
$("#divMain").append('<div id="' + metric.key + '" style="min-width: 310px; height: 200px; margin: 0 auto"></div>');
$('#' + metric.key).highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
},
title: {
text: metric.Title
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Messages'
},
plotLines: [
{
value: 0,
width: 1,
color: '#808080'
}
]
},
tooltip: {
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: metric.series
});
};
function ParseData(message) {
var jsonObj = JSON.parse(message);
$.each(jsonObj.Metrics, function(index, value) {
var metricName = value.Metric.Name.replace(' ', '');
if (metrics[metricName] == undefined) {
metrics[metricName] = {
"title": value.Metric.Name,
"key": metricName,
"series": [
{
name: value.Metric.Name,
data: []
}
],
}
AddChart(metrics[metricName]);
}
metrics[metricName].series.addPoint([new Date().getTime(), parseInt(value.Metric.CurrentValue)], true, false);
});
};
setInterval(function () {
var m = "{\"Metrics\": [{\"Metric\":{\"Name\":\"Queue 01\",\"CurrentValue\":\"0\",\"TimeStamp\":\"\\\x2FDate(1415826323291)\\\x2F\"}},{\"Metric\":{\"Name\":\"Queue 02\",\"CurrentValue\":\"3\",\"TimeStamp\":\"\\\x2FDate(1415826323344)\\\x2F\"}},{\"Metric\":{\"Name\":\"Queue 03\",\"CurrentValue\":\"9\",\"TimeStamp\":\"\\\x2FDate(1415826323405)\\\x2F\"}}]}";
ParseData(m);
}, 1000);
});
});
First, you have metrics declared as an array. Should be an empty object:
var metrics = {};
Second, the data structure you've created, metrics[metricName].series is not a Highcharts series object. It's an object you created and used to supply Highcharts data. To get the real series object, you'll have to get it back from the chart.
// getting the chart from the DOM, then the first series...
$("#"+metricName).highcharts().series[0].addPoint([new Date().getTime(), parseInt(value.Metric.CurrentValue)], true, false);
Updated fiddle.

Highcharts - remove points from series

Is it possible to remove certain points from a series?
I'm looking for some way to draw a chart with a fixed back period,
something like: the last 1 hour.
I know how to add points using dynamic update:
http://www.highcharts.com/demo/dynamic-update
But in my case the time interval between points is not constant,
so I can't just use the shift option of addPoint.
Thanks,
Omer
If you want to have the same, you can use the same logic as in addPoint, see: http://jsfiddle.net/JKCLx/1/
However, why can't you just use shift argument in addPoint()?
I think I found a partial answer to my own question:
I can iterate over the series datapoints like this:
http://api.highcharts.com/highcharts#Series.data
and then call point.Remove.
The problem with this solution is that it does not draw monitor style like in the example,
but rather it redrwas the entire chart on each change.
http://jsfiddle.net/JKCLx/
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function() {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(), // current time
y = Math.random();
series.addPoint([x, y], true, false);
// series.data[0].remove(false);
series.data[0].remove(true);
}, 1000);
}
}
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
})()
}]
});
});
});

Highstock returns incorrect x value (datetime) after zoom for column chart

After any sort of zoom (mouse drag, range selector, date input) the datetime returned from the point click event is usually incorrect. I've not yet found this problem when using an area chart, have found it using both bar and column chart.
To recreate: run the fiddle, zoom using the mouse across a few of the columns, click a datapoint. The alert will show the datetime returned. Notice it's different from the tooltip (which is correct).Usually fails after first click, even for the same datapoint.
BTW useUTC setting doesn't matter.
Fiddle: http://jsfiddle.net/jrEDT/
Code for completeness:
$(function() {
var seriesOptions = [],
yAxisOptions = [],
seriesCounter = 0,
names = ['MSFT'],
colors = Highcharts.getOptions().colors;
$.each(names, function(i, name) {
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename='+ name.toLowerCase() +'-c.json&callback=?', function(data) {
seriesOptions[i] = {
name: name,
data: data,
type: 'column'
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter++;
if (seriesCounter == names.length) {
createChart();
}
});
});
// create the chart when all data is loaded
function createChart() {
Highcharts.setOptions({
global: {
useUTC: false // datetime reflects time on db (ie, local) rather than GMT
}
});
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container',
zoomType: 'x'
},
exporting: {
enabled: false
},
rangeSelector: {
selected: 4
},
yAxis: {
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}],
offset: 25
},
plotOptions: {
series: {
cursor: 'pointer',
allowPointSelect: true,
point: {
events: {
click: function() {
var series = this.series.name;
var utc = this.x;
var d = Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x);
alert(d);
}
}
}
}
},
tooltip: {
formatter:function(a,b,c){
var d = Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x);
return d;
},
enable:true
},
series: seriesOptions
});
}
});
Thanks!
Have you tried to disable datagrouping http://api.highcharts.com/highstock#plotOptions.series.dataGrouping ?

Highcharts show real time value on Labels

I follow the following guide to create a live chart:
http://www.highcharts.com/documentation/how-to-use#live-charts
It catch the values and update the chart every '3' seconds. It works fine!
Now, is it possible to show the real time value on labels? Something like:
This should be change every polling..... Or at least, show the last generated value in other chart place?
This is my HTML/JS code to generate the chart:
<script type="text/javascript">
var chart; // global
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 30; // shift if the series is longer than 20
var series = chart.series[1],
shift = series.data.length > 30; // shift if the series is longer than 20
var series = chart.series[2],
shift = series.data.length > 30; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint([point[0], point[1]], true, shift);
chart.series[1].addPoint([point[0], point[2]], true, shift);
chart.series[2].addPoint([point[0], point[3]], true, shift);
setTimeout(requestData, 3000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Live data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 40 * 1000
},
yAxis: {
minPadding: 0.5,
maxPadding: 0.5,
showLastLabel: true,
title: {
text: '',
margin: 1
}
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%H:%M:%S', this.x) +'<br/>'+
'MDA: '+ this.y;
}
},
series: [{
name: 'Point1',
data: []
}, {
name: 'Point2',
data: []
}, {
name: 'Point3',
color: '#FF00FF',
data: []
}]
});
});
</script>
Here is the link of a topic on how to change legend text dynamically from highcharts forum. [http://highslide.com/forum/viewtopic.php?f=9&t=18805&p=76061&hilit=change+series+name#p76061][1]
[1]: http://highslide.com/forum/viewtopic.php?f=9&t=18805&p=76061&hilit=change%20series%20name#p76061 Hope it helps!

Resources