Auto-refresh Json data in Highcharts - javascript

I've been working this for past 4 days but still can figure out how to solve this issue:
The data in the database changes every 5 minutes.
I want to display the data in a new chart without refreshing the whole page.
CODE:
$(function () {
$(document).ready(function() {
$.getJSON("test2.php", function(json) {
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
renderTo: 'container',
defaultSeriesType: 'spline',
chart: {
type: 'area',
},
title: {
text: 'Transaction Count'
},
subtitle: {
text: '5 Minutes Count'
},
exporting: {
enabled: false
},
xAxis: {
categories:json,
title:{
text: 'Time Of The Day',
style: {
color: '#666666',
fontSize: '12px',
fontWeight: 'normal'
}
},
tickInterval: 4,
type: 'datetime',
labels: {
style: {
fontFamily: 'Tahoma'
},
}
},
yAxis: {
title: {
text: 'Number Of Transaction'
},
labels: {
formatter: function () {
return this.value;
}
}
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y:,.0f}</b>'
},
plotOptions: {
column: {colorByPoint: true},
area: {
marker: {
enabled: false,
symbol: 'circle',
radius: 5,
states: {
hover: {
enabled: true
}
}
}
}
},
colors: [
'green', //Buy
'#4572A7' //Paid
],
series: json
});
});
});
});

You can change the dataset, like this :
$('#container').highcharts().series[0].setData([129.2,144.0,...], false);
You can redraw, like this :
$('#container').highcharts().redraw();
So, what you need to do, is create a function that (1) first gets the data from the server, (2) then updates the data and (3) then redraws, like this :
var updateChart = function() {
$.getJSON('test2.json', function(data) {
var chart = $('#container').highcharts();
$.each(data, function(pos, serie) {
chart.series[pos].setData(serie, false);
});
chart.redraw();
});
}
To repeat this every 5 minutes, you can use setInterval, like this :
setInterval(function() {
$.getJSON('test2.json', function(data) {
var chart = $('#container').highcharts();
$.each(data, function(pos, serie) {
chart.series[pos].setData(serie, false);
});
chart.redraw();
});
}, 300000);

Instead of putting your Highchart script in the document.ready function, you can create a funcion getHighchart and put the code about into it. and depend on how many seconds you want the code to readload as below, but you have to be referencing the jquery js.
$(function () {
setInterval(getHighChart, 30000); //30 seconds onload="getHighChart()"
});
function getHighChart() {
//to containe you script for loading the chart
}

Related

Show data as a live stream, Highcharts

So What I have is a set of data stored, which I am able to access in Highchart easily. but Now what I need is to show the data as a live stream
like the following example :
https://www.highcharts.com/demo/dynamic-update
What I have done so far is Here :
<script type="text/javascript">
var xValues = [];
xValues = [1,4,3,9,3,4,4,6,4,5,3,4,3,3,1,3,2,3,2,3,4,4,3,3,4,3,5,3,6,7,3,2,5,7,4,6,7,3,6,7,4,7,4,7,3,2,5,6,7,4,3,4,6,6,7,4,6,6,7,3,6,7,3,2,4,5,6,5,9,8,4,6,2,1,5,8,5,8,2,6,3,8,4,7,3,6,1,5,8,0,2,4,7,5,8,3,7,9,3,7];
Highcharts.chart('ppg', {
chart: {
type: 'line'
},
title: {
text: 'ECG Data'
},
subtitle: {
text: ''
},
xAxis: {
crosshair: false
},
yAxis: {
title: {
text: 'Peaks'
}
},
tooltip: {
enable: false
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: '',
lineWidth: 2,
data: xValues,
animation: {
duration: 5000
}
}]
});
</script>.
How can my data flow like the above example? in 10 10 patches.
Here is the Working JSFiddle:
https://jsfiddle.net/abnitchauhan/3vj2afnt/
You can initially add only the first 10 points and then use chart load event function and set interval to add remaining points with shift argument:
var xValues = [],
counter = 11,
startValues;
xValues = [...];
startValues = xValues.slice(0, counter);
var chart = Highcharts.chart('ppg', {
chart: {
type: 'line',
events: {
load: function() {
var chart = this,
interval = setInterval(function() {
chart.series[0].addPoint(xValues[counter], true, true);
counter++;
if (counter === xValues.length - 1) {
clearInterval(interval);
}
}, 1000);
}
}
},
...
});
Live demo: https://jsfiddle.net/BlackLabel/7x9vrLqm/
API Reference:
https://api.highcharts.com/highcharts/chart.events.load
https://api.highcharts.com/class-reference/Highcharts.Series#addPoint
In your code event is missing which will trigger change per sec.
Something like this. I have used random number.
var xValues = [];
xValues = [1,4,3,9,3,4,4,6,4,5,3,4,3,3,1,3,2,3,2,3,4,4,3,3,4,3,5,3,6,7,3,2,5,7,4,6,7,3,6,7,4,7,4,7,3,2,5,6,7,4,3,4,6,6,7,4,6,6,7,3,6,7,3,2,4,5,6,5,9,8,4,6,2,1,5,8,5,8,2,6,3,8,4,7,3,6,1,5,8,0,2,4,7,5,8,3,7,9,3,7];
Highcharts.chart('ppg', {
chart: {
type: 'line',
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = Math.random();
y = Math.random();
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
title: {
text: 'ECG Data'
},
subtitle: {
text: ''
},
xAxis: {
crosshair: false
},
yAxis: {
title: {
text: 'Peaks'
}
},
tooltip: {
enable: false
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: '',
lineWidth: 2,
data: xValues,
animation: {
duration: 5000
}
}]
});
Working fiddle

Changing yAxis and plotOptions for drilldown

I am using HighCharts to visualize percentages from projects, which are downdrilled into variables which make the percentages!
I will give my code :
$(function () {
// Create the chart
var options = {
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Comparison'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
enabled: true,
text: 'Percentages',
style: {
fontWeight: 'normal'
}
},
labels: {
format: '{value}%'
}
},
legend: {
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: '',
colorByPoint: true,
data: []
}],
credits: {
enabled: false
},
drilldown: {
series: [{
name : '',
id: '',
data: []
}]
}
};
$.getJSON('/uploads/fraction.json', function (list) {
options.series = list;
});
$.getJSON('/uploads/drilldown.json', function (list2) {
options.drilldown.series = list2;
var chart = new Highcharts.Chart(options);
});
});
Example of the JSONs:
fraction.json
[{"name":"","colorByPoint":true,"data":[{"name":1,"y":80,"drilldown":1},{"name":2,"y":87,"drilldown":2},{"name":3,"y":105.71428571429,"drilldown":3},{"name":5,"y":"","drilldown":5},{"name":6,"y":53.160248409091,"drilldown":6}]}]
drilldown.json
[{"name":1,"id":1,"data":[["Total",2],["Estimated",2.5]]},{"name":2,"id":2,"data":[["Total",3.9],["Estimated",4.5]]},{"name":3,"id":3,"data":[["Total",3.7],["Estimated",3.5]]},{"name":5,"id":5,"data":[["Total",""],["Estimated",0.44]]},{"name":6,"id":6,"data":[["Total",0.233905093],["Estimated",0.44]]}]
I would like the graph to show percentages above the column and on the yAxis when the graph is first loaded, but absolute values when the drilldown is activated. I didn't manage to get it until now. Could you help me?
There are two ways of doing those changes - a static and dynamic way. Static way - define data labels and tooltip options for drilldown series.
Dynamic way - apply the options on drilldown/drillup events.
events: {
drilldown: function(options) {
this.yAxis[0].update({
labels: {
format: '{value}'
}
}, false, false);
options.seriesOptions.dataLabels = {
format: '{point.y:.1f}'
};
options.seriesOptions.tooltip = {
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}</b> of total<br/>'
};
},
drillup: function () {
this.yAxis[0].update({
labels: {
format: '{value}%'
}
}, false, false);
}
}
example: http://jsfiddle.net/d4fmaeea/
Two warnings:
In your json files, you have points which has value equals to "" which is not a valid type (must be number/null) and it may cause some issues, e.g. column with value 0 will have the same height as the column with value 10.
$.getJSON() is an asynchronous function. You use getJSON to assign list to options.series but that part may be executed after the chart was created so you would end up with the chart with no top-level series, only the drilldown ones.
Async part of code:
$.getJSON('/uploads/fraction.json', function (list) {
options.series = list;
});
$.getJSON('/uploads/drilldown.json', function (list2) {
options.drilldown.series = list2;
var chart = new Highcharts.Chart(options);
});

Highcharts - Show tooltip onClick instead of hover

I have tried the solution at https://stackoverflow.com/a/24206104/5653279 but to no avail as my Highcharts consist of 2 series of data.
Following the above solution returns me the error
Uncaught TypeError: Cannot read property 'category' of undefined
$(function () {
$('#container').highcharts({
chart: {
type: 'spline',
zoomType: 'xy',
events: {
load: function(){
this.myTooltip = new Highcharts.Tooltip(this, this.options.tooltip);
}
}
},
tooltip: {
enabled: false,
headerFormat: '<b>{point.x: %A, %b %e at %I:%M %p}</b><br>',
shared: true,
borderRadius: 10,
crosshairs: [true, false] //x,y
},
plotOptions: {
series: {
stickyTracking: false,
events: {
click: function(evt) {
this.chart.myTooltip.refresh(evt.point, evt);
},
mouseOut: function() {
this.chart.myTooltip.hide();
}
}
}
},
title: {
text: 'Glucose/Carbohydrate'
},
subtitle: {
text: 'Ratio between Glucose and Glucose'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
month: '%e/%b',
},
title: {
text: 'Date'
}
},
yAxis: [{ // Glucose yAxis
labels: {
format: '{value}mmol/L',
style: {
color: Highcharts.getOptions().colors[0]
}
},
title: {
text: 'Glucose',
style: {
color: Highcharts.getOptions().colors[0]
}
}
}, { // Carbohydrate yAxis
title: {
text: 'Carbohydrate',
style: {
color: Highcharts.getOptions().colors[1]
}
},
labels: {
style: {
color: Highcharts.getOptions().colors[1]
}
},
opposite: true
}],
series: [{
name: 'Glucose',
data: glucose,
marker: {
enabled: true
},
tooltip: {
valueSuffix: ' mmol/L'
}
},{
name: 'Carbohydrate',
data: carbohydrate,
dashStyle: 'shortdot',
yAxis: 1,
marker: {
enabled: true
}
}
]}
);
});
However, the error would be "solved" if I edit plotOptions as seen.
plotOptions: {
series: [{
stickyTracking: false,
events: {
click: function(evt) {
this.chart.myTooltip.refresh(evt.point, evt);
},
mouseOut: function() {
this.chart.myTooltip.hide();
}
}
},
{
stickyTracking: false,
events: {
click: function(evt) {
this.chart.myTooltip.refresh(evt.point, evt);
},
mouseOut: function() {
this.chart.myTooltip.hide();
}
}
}]
},
But still, the tooltip does not show when I clicked on any point.
Solved the issue!
Just changed
this.chart.myTooltip.refresh(evt.point, evt);
to
this.chart.myTooltip.refresh([evt.point], evt);
But the only limitation to this fix is if there's multiple series (e.g. Line A and B) and the data of both series falls on the same X-Axis (e.g. on the same date), clicking on it will only show the tooltip of that particular series's data (if I click on series A's data, the tooltip only shows A's data without B, even though they are sharing the same X-Axis).

Set enable/disable 3D mode with Highcharts

I made a form to change values dinamically in my chart. I can change title, subtitle, etc, but... How can I change to set enabled or disabled 3D mode??
$(document).ready(function () {
//Title inputText
$('#gra_title').blur(function(){
chart.setTitle({ text: $('#gra_title').attr("value") });
});
//Subtitle inputText
$('#gra_subtitle').blur(function(){
chart.setTitle(null, { text: $('#gra_subtitle').attr("value") });
});
//Credits checkbox
$('#gra_credits_visible').click(function () {
if ($('#gra_credits_visible').is(':checked')){
chart.credits.show();
}else{
chart.credits.hide();
}
});
......... //More events to change chart
//3D checkbox - MY PERSONAL BUG
$('#gra_3d_visible').click(function () {
if ($('#gra_3d_visible').is(':checked')){
chart.options.chart.options3d.enabled = true;
}else{
chart.options.chart.options3d.enabled = false;
}
chart.redraw();
// return TRUE or FALSE, but don't change 3D/2D mode
alert(chart.options.chart.options3d.enabled);
});
});
This is my chart:
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
marginRight: 0,
events: {
load: function () {
this.credits.element.onclick = function () {
window.open('http://www.url.com', '_blank');
}
}
},
marginTop: 80,
type: 'column',
options3d: {
enabled: true,
alpha: 15,
beta: 15,
viewDistance: 25,
depth: 90
}
},
plotOptions: {
column: {
depth: 90
}
},
credits: {
enabled: true,
text: 'MyWeb.com',
style: {
cursor: 'pointer',
color: '#909090',
fontSize: '10px'
}
},
title: {
text: 'Población Mundial'
},
subtitle: {
text: 'Fuente: Wikipedia.org'
},
xAxis: {
title: {
text: 'Continentes'
},
categories: ['Africa', 'América', 'Asia', 'Europa', 'Oceanía']
},
yAxis: {
title: {
text: 'Población (millones)'
},
},
series: [{
name: 'Año 1800',
data: [107, 31, 635, 203, 2]
}]
});
I've looking for in API Documentation but I didn't find nothing.
Unfortunately you need destroy and create chart, update option for 3d is not available.

How can i call java script function by clicking x Axis label on Highchart

i will be thankful to you all if you can tell me how to call java script function clicking by xAxis label on Highchart.
belowe here there's my code.
thanks in advance.
var options = {
chart: {
renderTo: 'container',
type: 'bar',
backgroundColor: 'rgba(100, 100, 100, 0.2)',
width: 1500,
height: 800,
...
},
title: {
....
},
credits: {
enabled: false
},
legend: {
enabled: false
},
xAxis: {
....
},
yAxis:{
...
},
labels: {
style: {
color: 'black',
fontWeight: 'bold'
}
}
},
plotOptions: {
series: {
stacking: 'normal'
}
},
tooltip: {
....
},
series: []
};
Here how i call my
$(document).ready(function() {
var chart = new Highcharts.Chart(options);
});
PS: I found this way to call function by clicking on labels but it doesn't work in my case
$(function () {
$('#container').highcharts({
chart: {
renderTo: 'container',
type: 'bar',
},
legend: {
enabled: false
},
xAxis: {
categories: ['chr1','chr2','chr3','chr4'],
labels: {
formatter: function() {
return '<a href="http://www.w3schools.com">'+
this.value +'</a>';
}
}
},
series: [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5]
}]
},function(chart){
$.each(chart.xAxis[0].ticks,function(i,tick){
tick.label.on('click',function(){
alert(tick.pos);
});
});
});
});
Jsfiddle
This is line where you create labels:
return '<a href="http://www.w3schools.com">'+
this.value +'</a>';
So you can simply change to this:
return '<a href="#" onclick="myFun()">'+
this.value +'</a>';
And should work.

Categories