HighCharts with Dynamic Data not working - javascript

I have a ASP.NET MVC project with SignalR.
I have a page with a HighChart and the script looks like this:
$(function () {
window.Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'line',
marginRight: 10
},
title: {
text: 'GMAS Queues'
},
xAxis: {
type: 'datetime',
tickInterval: 500,
labels: {
enabled: false
}
},
yAxis: {
title: {
text: 'Queue Count'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
name: 'Processing Queues'
}]
});
});
$.connection.hub.logging = true;
// Reference the auto-generated proxy for the hub.
var chartData = $.connection.processingQueuesHub;
// Create a function that the hub can call back to display messages.
chartData.client.updateQueueCounts = function (data) {
//$.each(data, function(i, item) {
// // Add the message to the page.
// $('#chartDataLog').append('<li><strong>' + htmlEncode(item.QueueName)
// + '</strong>: ' + htmlEncode(item.Length) + '</li>');
//});
// set up the updating of the chart.
var series = chart.series[0];
$.each(data, function (i, item) {
if (item.QueueName == "Queue A") {
var x = Date.parse(item.Date),
y = item.Length;
series.addPoint([x, y], true, false);
}
});
};
However, I see the graph but not the points.
The strange part is the series data points are there:
Anyone know why HighCharts is not rendering the points?
Thanks, Bill N

I have to thank my good friend and co developer for figuring this out. He is a smarter and braver man than me. :) He went to the highcharts source and found that the highcharts breaks if you add to the graph series before the initial animation is completed. The animation is why the clip-rect is zero-width (it animates from zero to full width over 1s when you first create the chart). You end up adding a point to the series before this animation even really starts. This kills the animation but it doesn’t fix the width of the clip-rect. The fix is to add animation is false for the series.
series: [{ name: 'Processing Queues', data: [], animation: false }]

It looks like you are not defining what your chart.series is until it is created. The line in your ajax is as follows and its not waiting for DOM ready:
var series = chart.series[0];
But you do not define chart until $(document).ready(function () {.... Try keeping your chart object in scope of your ajax.

Related

How to highlight specific Point with Highcharts Js

I have a simple Highchart with a dataset of up to 1000 datas. There are only y values the x values are generated automatically. Also, the values come from my nodejs server so please don't be surprised about the notation.
Now I want 3 special values whose x and y values are known to be highlighted. In which way doesn't matter for now.
One possibility would be to show the point at the location, otherwise they are not displayed. The problem I have is that I don't know how to control a specific point.
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'chart-emg1',
type: 'line'
},
title: {
text: 'EMG 1'
},
xAxis: {
tickInterval: 1
},
yAxis: {
title: { text: 'Voltage'}
},
series: [{
data: [<%-data1 %>]
}]
});
You can use the load event and update specific points. For example:
events: {
load: function() {
this.series[0].points.forEach(point => {
const isPointToHighlight = pointsToHighlight.some(
p => p.x === point.x && p.y === point.y
);
if (isPointToHighlight) {
point.update({
color: 'red',
marker: {
enabled: true
}
}, false);
}
});
this.redraw();
}
}
Live demo: http://jsfiddle.net/BlackLabel/tLd3j78f/
API Reference:
https://api.highcharts.com/highcharts/chart.events.load
https://api.highcharts.com/class-reference/Highcharts.Point#update

Chart update everytime on Loading second array : Highcharts, Javascript

So, What I have is a condition in a MySQL to show the first 1000 data points first and then the other 2000 datapoints after that in Highcharts.
if lastindex==0:
cur.execute("SELECT data,value FROM table where id<1001")
else:
cur.execute("SELECT data,value FROM table where id>1001 and id<3000")
data = cur.fetchall()
//python Code to fetch SQL data
Now what I am doing is that I am rendering that data into the Highcharts, the data is being rendered. but the problem arises that after showing the first 1000 data points, the Highcharts value starts from 0 and then shows the other 2000 points
the data is not displaying continuously as it should plot the send array data just after the end of the first data.
I think the Highcharts is being called Twice, What can I do to append the 2nd set of data to the first set without reloading the whole chart.
Here's a snip of my Highchart's js
Highcharts.chart("chartcontainer", {
chart: {
type: 'line',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function() {
var series = this.series[0],
chart = this;
setInterval(function() {
//some logic regarding the chart
//..
v = {
y: y,
x: x
};
console.log("V value", v);
series.addSeries(v, false, true);
counter++;
localcounter++;
} else
{
oldcounter=counter;
flagToreload=1;
}
}, 1000/130);
setInterval(function() {
chart.redraw(false);
}, 100);
}
}
},
time: {
useUTC: false
},
title: {
text: 'Live random data'
},
xAxis: {
type: 'Value',
gridLineWidth: 1
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}],
gridLineWidth: 1
},
tooltip: {
headerFormat: '<b>{series.name}</b><br/>',
pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f}'
},
exporting: {
enabled: false
},
series: [{
animation: false,
name: 'Random data',
data: (function() {
// generate an array of random data
var data = [],
time = counter,
i;
for (i = -1000; i <= 0; i += 1) {
data.push([
counter,
null
]);
}
return data;
}())
}]
});
What I want is just to append the event data rather than loading the whole chart.
How can I reload a particular Highchart value without reloading the whole chart ?
What do you think about updating the current series with new data, which will be an array of old data merged with the new one?
chart: {
events: {
load(){
let chart = this,
currentSeries = chart.series[0],
newData;
newData = [...currentSeries.userOptions.data, ...data1]
setTimeout(()=> {
chart.series[0].update({
data: newData
})
}, 5000)
}
}
},
See the demo

javascript highcharts builder function

I am trying to make a function which will be building Highcharts charts dynamically based on parameters passed. I do it the following way:
function makeChart(name, title, series)
{
var options = {
chart: {
type: 'areaspline',
renderTo: name
},
credits: { enabled: false },
legend: { enabled: true },
title: {
text: title
},
xAxis: {
type: 'datetime'
},
yAxis: {
gridLineDashStyle: 'dot',
title: {
text: 'Quantity'
}
},
plotOptions: {
areaspline: {
animation: false,
stacking: '',
lineWidth: 1,
marker: { enabled: false }
}
},
series: [] //chart does not display except title. It will draw if I paste the data here manually
};
this.chart = new Highcharts.Chart(options);
for (index = 0; index < series.length; ++index) {
options.series[index] = {'name':series[index][0], 'data':series[index][1], 'color':series[index][2], 'fillOpacity': .3};
}
}
makeChart('container2', 'second chart', [['thisisname1', [20,21,22,23,24,25,26,27,28], '#d8d8d8']]);//calling function with test parameters
But everything I can see is the charts title. I guess the problem is in adding data to series array. I tried to add it with several ways but it did not work, although I see that the data has been added if I console.log(options.series). Any ideas how to fix that? Thank you.
Place this.chart = new Highcharts.Chart(options); after the for loop.
You're adding the data after the chart has been initialized, for it to work this way you need to tell HighCharts to redraw itself, easier option is to init after the loop. :)

HighCharts - dynamic graph & no tick mark on the right hand side dual axis

I'm new to high charts.
I'm dynamically making 2 ajax calls(inside getData() Function) and plotting the high chart with 2 series(with 2 y axis).
each ajax call with return the json data.
1st json data (sample)
[{"dt":"May 15, 2000","index":"2,007.030850"},{"dt":"May 16, 2000","index":"2,025.956108"}]
2nd json data (sample)
[{"dt":"May 15, 2000","nav":"145.236000"},{"dt":"May 16, 2000","nav":"146.602974"}]
I'm creating two series with 2 ajax calls. in the 2nd ajax call, i'm dynamically adding a y-axis for the 2nd series data.
$(document).ready(function() {
function getData() {
var chart = Highcharts.charts[0];
/* 1st Ajax Call to get the json data to plot the first series */
$.ajax({
type: 'POST',
dataType: 'json',
url: '/Six/TSServlet?file=ivv-sixIshareFundsHistoryIndex.json',
data: '',
async: false,
success: function(data) {
var categories1 = [];
var seriesData1 = [];
var yaxis;
$.each(data, function(i, e) {
categories1.push(e.dt);
/* below step to remove , is not important, done for my program */
yaxis = parseFloat(e.index.replace(/,/g, ''));
seriesData1.push(yaxis);
})
// add x-axis catagories
chart.xAxis[0].update({
categories: categories1,
tickInterval: 150
}, true);
// add the 1st series
chart.series[0].setData(seriesData1);
}
});
/* 2nd Ajax Call to get the json data to plot the second series */
$.ajax({
type: 'POST',
dataType: 'json',
url: '/Six/TSServlet?file=ivv-sixIshareFundsHistoryNav.json',
data: '',
async: false,
success: function(data) {
var categories2 = [];
var seriesData2 = [];
var yaxis;
$.each(data, function(i, e) {
categories2.push(e.dt);
/* below step to remove , is not important, done for my program */
yaxis = parseFloat(e.nav.replace(/,/g, ''));
seriesData2.push(yaxis);
})
/* This is the problem area, dynamically adding a dual y axis for the 2nd series */
chart.addAxis({ // Secondary yAxis
id: 'NAV-Series-Axis',
title: {
text: 'NAV Series'
},
lineWidth: 2,
lineColor: '#08F',
opposite: true
});
// add the 2nd series
chart.addSeries({name: "NAV Series",yAxis: 'NAV-Series-Axis',data: seriesData2});
}
});
} //getdata function ends here .............
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
renderTo: 'container',
events: {
load: function() {
var series = this.series[0];
getData();
}
}
},
title: {
text: 'Six Share Funds History'
},
labels: {
formatter: function() {
return this.value + ' %';
}
},
xAxis: {
tickLength: 10
},
tooltip: {
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' + this.x + '<br/>' + Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
series: [{
"Name": []
}]
});
});
});
My issue is i'm getting 2 axis for 2 series graph, but no tick marks on the right hand side y-axis. how to solve this issue? ideally i should see 100(one tick mark), 200 (one tick mark) etc on the right hand side blue bar(just like left hand side y-axis has 500,1000 etc)
Please see the screen shot, i dont see the tick marks on the right hand side blue bar (for the 2nd series graph)
Edited to add jsp:
<div id='TimeSeriesId'>
<div id="container" style="width: 100%; height: 600px;"></div>
</div>
You can add several Y-axes simply by making yAxis an array with more than 1 element. Each can have all of the usual axis attributes (see highcharts API).
yAxis: [{ // Primary yAxis
labels: { ...
},
title: { ...
},
opposite: true
}, { // Secondary yAxis
title: { ...
},
labels: { ...
}
}, { // Tertiary yAxis
title: { ...
},
labels: { ...
},
opposite: true
}],
...
To dynamically add them, use chart.yAxis = new Array(); chart.yAxis[1].title = ... etc.

highcharts spline with multiple series update every few seconds

I am trying to get a spline chart with 2 series that updates every few seconds. I have spent lots of time searching through various examples and I can get many different things to work but NOT this. I just cant seem to find an example that is exactly what I am trying to do out there.
I have the following json that is returned via ajax:
[{"name":"Test1","data":[[1415567095000,2117]]},{"name":"Test2","data":[[1415567095000,2414]]}]
Below is what I have for the chart definition. This is a slightly modified example that I found but I just cant figure out how to get this to work. I know that it should not be that complex and since I am new to javascript, I suspect it will be something simple that I just don't see. I know that I need to define multiple series and then perform addPoint with a shift but I cant seem to get it to work.
<script type="text/javascript">
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'spline',
},
title: {
text: 'Dynamic RPS'
},
subtitle: {
text: 'US East'
},
xAxis: {
type: 'datetime',
},
yAxis: {
min: 0,
title: {
text: 'RPS '
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{}]
};
setInterval(function() {
$.getJSON('test.php', function(data) {
options.series = data;
var chart = new Highcharts.Chart(options);
});
}, 20000);
});
</script>
Any help is greatly appreciated !!
Assuming your test.php will return a single new point on each call, I'd code it like this:
var chart = null;
function callAjax(){
$.getJSON('test.php', function(data) {
if (chart === null){ // first call, create the chart
options.series = data;
chart = new Highcharts.Chart(options);
} else {
var seriesOneNewPoint = data[0].data[0]; // subsequent calls, just get the point and add it
var seriesTwoNewPoint = data[1].data[0];
chart.series[0].addPoint(seriesOneNewPoint, false, false); // first false is don't redraw until both series are updated
chart.series[1].addPoint(seriesTwoNewPoint, true, false); // second false is don't shift
}
setTimeout(callAjax, 20000); // queue up next ajax call
});
}
callAjax();
Here's an example. Note, it just draws the same point over and over again.

Categories

Resources