Highcharts - Update column chart in real time - javascript

I'm trying to update dynamically a column type Highcarts with no luck. This is the demo code for the column chart:
HTML:
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
JS:
Highcharts.chart('container', {
chart: {
type: 'column',
},
title: {
text: ''
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: ''
},
max: 100
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}m/sĀ²rms'
}
}
},
"series": [
{
"name": "",
"colorByPoint": true,
"data": [
{
"name": "",
"y": 30
}
]
}
]
});
I would like to update the y value dynamically. I tried to add this on the charts section of the JS:
Highcharts.chart('container', {
chart: {
type: 'column',
// This is my new code to update Y every second
load : function() {
var series = this.series[0];
setInterval(function() {
y = Math.random();
series.data.y([y]);
}, 1000);
}
// End of my new code
},
title: {
text: ''
},
xAxis: {
type: 'category'
},
[...]
JSFiddle: https://jsfiddle.net/af8p9yon/
Can someone tell me how can I archieve this with Javascript? Thanks in advance.

You have two mistakes in your code, there is no events property and you should use setData or update method:
using setData method
events: {
load: function() {
var series = this.series[0];
setInterval(function() {
y = Math.random();
series.setData([y]);
}, 1000);
}
}
using update method
events: {
load: function() {
var series = this.series[0];
setInterval(function() {
y = Math.random() * 100;
series.update({
data: [y],
}, true)
}, 1000);
}
}
Live demo: https://jsfiddle.net/BlackLabel/Louath3b/
API:
https://api.highcharts.com/class-reference/Highcharts.Series#setData
https://api.highcharts.com/class-reference/Highcharts.Series#update

Related

HighCharts does not add a new points

I am trying to set up a simple weather station with esp8266 and plot and display the obtained data in graphs. I'm trying to use HighCharts for this task. Now I'm having a problem that HighCharts does not add a new point to the graph.
My code:
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript" src="jquery-1.9.0.min.js"></script>
<style>
body {
min-width: 310px;
max-width: 1280px;
height: 500px;
margin: 0 auto;
}
h2 {
font-family: Arial;
font-size: 2.5rem;
text-align: center;
}
</style>
<body>
<h2>ESP Weather Station</h2>
<div id="chart-temperature" class="container"></div>
<div id="chart-humidity" class="container"></div>
<div id="chart-pressure" class="container"></div>
<script>
var value1 = <?php echo $value1; ?>;
var value2 = <?php echo $value2; ?>;
var value3 = <?php echo $value3; ?>;
var reading_time = <?php echo $reading_time; ?>;
var chartT = new Highcharts.Chart({
chart:{ renderTo : 'chart-temperature' },
title: { text: 'BME280 Temperature' },
series: [{
showInLegend: false,
data: value1
}],
plotOptions: {
line: { animation: false,
dataLabels: { enabled: true }
},
series: { color: '#059e8a' }
},
xAxis: {
type: 'datetime',
categories: reading_time
},
yAxis: {
title: { text: 'Temperature (Celsius)' }
//title: { text: 'Temperature (Fahrenheit)' }
},
credits: { enabled: false }
});
setInterval(function ( ) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var x = (new Date()).getTime(),
y = parseFloat(this.responseText);
//console.log(this.responseText);
if(chartT.series[0].data.length > 4) {
chartT.series[0].addPoint([x, y], true, true, true);
} else {
chartT.series[0].addPoint([x, y], true, true, true);
}
}
};
xhttp.open("GET", "/esp-chart.php", true);
xhttp.send();
}, 3000 ) ;
var chartH = new Highcharts.Chart({
chart:{ renderTo:'chart-humidity' },
title: { text: 'BME280 Humidity' },
series: [{
showInLegend: false,
data: value2
}],
plotOptions: {
line: { animation: false,
dataLabels: { enabled: true }
}
},
xAxis: {
type: 'datetime',
//dateTimeLabelFormats: { second: '%H:%M:%S' },
categories: reading_time
},
yAxis: {
title: { text: 'Humidity (%)' }
},
credits: { enabled: false }
});
var chartP = new Highcharts.Chart({
chart:{ renderTo:'chart-pressure' },
title: { text: 'BME280 Pressure' },
series: [{
showInLegend: false,
data: value3
}],
plotOptions: {
line: { animation: false,
dataLabels: { enabled: true }
},
series: { color: '#18009c' }
},
xAxis: {
type: 'datetime',
categories: reading_time
},
yAxis: {
title: { text: 'Pressure (hPa)' }
},
credits: { enabled: false },
});
</script>
</body>
</html>
Now I'm trying to just add a new point to the temperature graph, ignoring humidity and pressure. That's what I get And the point keeps on reloading over and over again. When I reload the page I see normally spaced points, but after a while it moves to one point as shown in the picture. Is there any way to plot the data continuously?
I tried to reproduce your case to understand the issue and here are my conclusions:
Don't use the true flag for a shift in the addPoint feature - it deletes the previous point - https://api.highcharts.com/class-reference/Highcharts.Series#addPoint
You have defined the xAxis type as 'datatime' and trying to assign the categories - it is also a mistake. The category type is a different thing.
xAxis: {
type: 'datetime',
categories: reading_time
},
Demo: https://jsfiddle.net/BlackLabel/45Ltwbcx/

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

How do i set the X-Axis as Date Array in highcharts.js simple highcharts.chart plot or .stockChart?

I can succesffuly chart the data in a table on mysql
$sql = "SELECT TradeDate as date, LScore2 as L FROM levermann_kurz WHERE Stock_short='MSFT' ORDER BY TradeDate desc";
$stock2 = mysqli_query($mysqli,$sql);
$stock2 = mysqli_fetch_all($stock2,MYSQLI_ASSOC);
$stock2 = json_encode(array_column($stock2,'L'),JSON_NUMERIC_CHECK);
and the body
<script type="text/javascript">
// load("getdata.php")
var data_stock1 = <?php echo $stock1; ?>;
var data_stock2 = <?php echo $stock2; ?>;
Highcharts.chart('container', {
title: {
text: 'Levermann Scores'
},
subtitle: {
text: 'TradeFlags'
},
// xAxis: {
// categories: dates
// },
yAxis: {
title: {
text: 'Levermann Score'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
plotOptions: {
series: {
label: {
connectorAllowed: false
},
//pointStart: 0
}
},
series: [{
name: 'AAPL',
data: data_stock1
}, {
name: 'MSFT',
data: data_stock2
// }, {
// name: 'External Data',
// data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227]
}],
responsive: {
rules: [{
condition: {
maxWidth: 500
},
chartOptions: {
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'bottom'
}
}
}]
}
});
</script>
</body>
But just can't get it to display the Date array as the x-Axis
It just has values 0,1,2,3,4,... etc.
What am i doing wrong? How do you set the x-axis array in the highchart plot?
I thought you could simply pass through a 2 column array with Dates in the first column and Values in the second column ?
Please help!
I have looked on highcharts documentation but it doesnt seem to explain to me how i should pass the data to the chart container. which format it should be?
CONSOLE LOG:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
</head>
<body>
<div id="container" style="height: 400px; max-width: 800px"></div>
<script type="text/javascript">
// load("getdata.php")
var data_stock1 = [3,2,2,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,3,2,3,2,2,1,-1,0,0,0,0,0,1,1,0,0,-1,0,-1,-1,-1,-1,-1,0,0];
var data_stock2 = [2,3,2,2,2,2,2,2,2,2,2,2,2,1,2,2,3,2,3,3,1,2,0,2,2,2,1,2,2,2,2,2,2,1,2,2,1,2,2,2,2,1,1,2];
var data_datearray = ["2018-05-25","2018-06-01","2018-06-08","2018-06-15","2018-06-22","2018-06-27","2018-07-06","2018-07-20","2018-07-27","2018-08-03","2018-08-10","2018-08-17","2018-08-24","2018-08-31","2018-09-07","2018-09-14","2018-09-21","2018-09-28","2018-10-05","2018-10-12","2018-10-19","2018-10-26","2018-11-02","2018-11-09","2018-11-16","2018-11-23","2018-11-30","2018-12-07","2018-12-14","2018-12-21","2018-12-28","2019-01-04","2019-01-11","2019-01-18","2019-01-25","2019-02-01","2019-02-08","2019-02-15","2019-02-22","2019-03-01","2019-03-08","2019-03-15","2019-03-22","2019-03-29"];
//var seriesOptions = [], seriesCounter = 0, names = ['MSFT', 'AAPL', 'GOOG'];
/**
* Create the chart when all data is loaded
* #returns {undefined}
*/
//function createChart() {
Highcharts.stockChart('container', {
///
title: {
text: 'Levermann Scores'
},
xAxis: {
type: 'datetime',
categories: data_datearray
},
series: [{
name: 'AAPL',
data: data_stock1
}, {
name: 'MSFT',
data: data_stock2
}]
////
// responsive: {
// rules: [{
// condition: {
// maxWidth: 500
// },
// chartOptions: {
// legend: {
// layout: 'horizontal',
// align: 'center',
// verticalAlign: 'bottom'
// }
// }
// }]
// }
});
// end of container }];
//}
console.log(data_stock1)
</script>
</body>
i can get the date into this format with two columns but it wont work in the chart
var data_dual = [{"date":"2018-05-25","L":"3"},{"date":"2018-06-01","L":"2"},{"date":"2018-06-08","L":"2"},{"date":"2018-06-15","L":"3"},{"date":"2018-06-22","L":"3"},{"date":"2018-06-27","L":"3"},{"date":"2018-07-06","L":"3"},{"date":"2018-07-20","L":"3"},{"date":"2018-07-27","L":"3"},{"date":"2018-08-03","L":"3"},{"date":"2018-08-10","L":"3"},{"date":"2018-08-17","L":"3"},{"date":"2018-08-24","L":"3"},{"date":"2018-08-31","L":"3"},{"date":"2018-09-07","L":"3"},{"date":"2018-09-14","L":"2"},{"date":"2018-09-21","L":"3"},{"date":"2018-09-28","L":"3"},{"date":"2018-10-05","L":"2"},{"date":"2018-10-12","L":"3"},{"date":"2018-10-19","L":"2"},{"date":"2018-10-26","L":"3"},{"date":"2018-11-02","L":"2"},{"date":"2018-11-09","L":"2"},{"date":"2018-11-16","L":"1"},{"date":"2018-11-23","L":"-1"},{"date":"2018-11-30","L":"0"},{"date":"2018-12-07","L":"0"},{"date":"2018-12-14","L":"0"},{"date":"2018-12-21","L":"0"},{"date":"2018-12-28","L":"0"},{"date":"2019-01-04","L":"1"},{"date":"2019-01-11","L":"1"},{"date":"2019-01-18","L":"0"},{"date":"2019-01-25","L":"0"},{"date":"2019-02-01","L":"-1"},{"date":"2019-02-08","L":"0"},{"date":"2019-02-15","L":"-1"},{"date":"2019-02-22","L":"-1"},{"date":"2019-03-01","L":"-1"},{"date":"2019-03-08","L":"-1"},{"date":"2019-03-15","L":"-1"},{"date":"2019-03-22","L":"0"},{"date":"2019-03-29","L":"0"}];
or using UNIX_TIMESTAMP i converted the date format into timestamps:
var data_dual = [{"date":"1527206400","L":"3"},{"date":"1527811200","L":"2"},{"date":"1528416000","L":"2"},{"date":"1529020800","L":"3"},{"date":"1529625600","L":"3"},{"date":"1530057600","L":"3"},{"date":"1530835200","L":"3"},{"date":"1532044800","L":"3"},{"date":"1532649600","L":"3"},{"date":"1533254400","L":"3"},{"date":"1533859200","L":"3"},{"date":"1534464000","L":"3"},{"date":"1535068800","L":"3"},{"date":"1535673600","L":"3"},{"date":"1536278400","L":"3"},{"date":"1536883200","L":"2"},{"date":"1537488000","L":"3"},{"date":"1538092800","L":"3"},{"date":"1538697600","L":"2"},{"date":"1539302400","L":"3"},{"date":"1539907200","L":"2"},{"date":"1540512000","L":"3"},{"date":"1541116800","L":"2"},{"date":"1541721600","L":"2"},{"date":"1542326400","L":"1"},{"date":"1542931200","L":"-1"},{"date":"1543536000","L":"0"},{"date":"1544140800","L":"0"},{"date":"1544745600","L":"0"},{"date":"1545350400","L":"0"},{"date":"1545955200","L":"0"},{"date":"1546560000","L":"1"},{"date":"1547164800","L":"1"},{"date":"1547769600","L":"0"},{"date":"1548374400","L":"0"},{"date":"1548979200","L":"-1"},{"date":"1549584000","L":"0"},{"date":"1550188800","L":"-1"},{"date":"1550793600","L":"-1"},{"date":"1551398400","L":"-1"},{"date":"1552003200","L":"-1"},{"date":"1552608000","L":"-1"},{"date":"1553212800","L":"0"},{"date":"1553817600","L":"0"}];
but using this array data_dual in the series will just render a chart with blank.
You need to use a datetime axis and provide dates as timestamps or as a Date objects, in the first elemets of the data array:
Highcharts.chart('container', {
xAxis: {
type: 'datetime'
},
series: [{
data: [
[1262304000000, 29.9],
[1267401600000, 71.5],
[1270080000000, 106.4]
]
}]
});
Or as an object:
series: [{
data: [{
x: 1262304000000,
y: 29.9
},
{
x: 1267401600000,
y: 71.5
},
{
x: 1270080000000,
y: 106.4
}
]
}]
Live demo: http://jsfiddle.net/BlackLabel/7tov823n/
API Reference: https://api.highcharts.com/highcharts/series.column.data

Drilldown in highmaps - how to remove a series

I am currently trying to create a drilldown map on Highmaps using this example:
http://www.highcharts.com/maps/demo/map-drilldown
I have got this to work with my own data for a different country correctly.
The code from this example is:
$(function () {
var data = Highcharts.geojson(Highcharts.maps['countries/us/us-all']),
// Some responsiveness
small = $('#container').width() < 400;
// Set drilldown pointers
$.each(data, function (i) {
this.drilldown = this.properties['hc-key'];
this.value = i; // Non-random bogus data
});
// Instanciate the map
Highcharts.mapChart('container', {
chart: {
events: {
drilldown: function (e) {
if (!e.seriesOptions) {
var chart = this,
mapKey = 'countries/us/' + e.point.drilldown + '-all',
// Handle error, the timeout is cleared on success
fail = setTimeout(function () {
if (!Highcharts.maps[mapKey]) {
chart.showLoading('<i class="icon-frown"></i> Failed loading ' + e.point.name);
fail = setTimeout(function () {
chart.hideLoading();
}, 1000);
}
}, 3000);
// Show the spinner
chart.showLoading('<i class="icon-spinner icon-spin icon-3x"></i>'); // Font Awesome spinner
// Load the drilldown map
$.getScript('https://code.highcharts.com/mapdata/' + mapKey + '.js', function () {
data = Highcharts.geojson(Highcharts.maps[mapKey]);
// Set a non-random bogus value
$.each(data, function (i) {
this.value = i;
});
// Hide loading and add series
chart.hideLoading();
clearTimeout(fail);
chart.addSeriesAsDrilldown(e.point, {
name: e.point.name,
data: data,
dataLabels: {
enabled: true,
format: '{point.name}'
}
});
});
}
this.setTitle(null, { text: e.point.name });
},
drillup: function () {
this.setTitle(null, { text: 'USA' });
}
}
},
title: {
text: 'Highcharts Map Drilldown'
},
subtitle: {
text: 'USA',
floating: true,
align: 'right',
y: 50,
style: {
fontSize: '16px'
}
},
legend: small ? {} : {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
colorAxis: {
min: 0,
minColor: '#E6E7E8',
maxColor: '#005645'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
plotOptions: {
map: {
states: {
hover: {
color: '#EEDD66'
}
}
}
},
series: [{
data: data,
name: 'USA',
dataLabels: {
enabled: true,
format: '{point.properties.postal-code}'
}
}],
drilldown: {
activeDataLabelStyle: {
color: '#FFFFFF',
textDecoration: 'none',
textOutline: '1px #000000'
},
drillUpButton: {
relativeTo: 'spacingBox',
position: {
x: 0,
y: 60
}
}
}
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/maps/highmaps.js"></script>
<script src="https://code.highcharts.com/maps/modules/data.js"></script>
<script src="https://code.highcharts.com/maps/modules/drilldown.js"></script>
<script src="https://code.highcharts.com/maps/modules/exporting.js"></script>
<script src="https://code.highcharts.com/maps/modules/offline-exporting.js"></script>
<script src="https://code.highcharts.com/mapdata/countries/us/us-all.js"></script>
<div id="container" style="height: 500px; min-width: 310px; max-width: 800px; margin: 0 auto"></div>
From my understanding, when a user clicks on a particular state, a separate js file containing the geo information for that state is loaded. However, I think that there is something missing from the code in that when there is no line of code which removes the data from the state-level js file once the user clicks 'Back to USA' and chooses another state. This results in some overlap i.e. when I click California, the California js file is called. The california state map remains under subsequent maps once I call another state. This is not hugely noticeable for this map due to it's square-like shape. However, in my example I can still see previously-loaded states (at a very small size) once I load another.
Can anyone give some insight into how I could get the previously-loaded state-level map to be removed once the user clicks on a different state?
Thanks in advance.
Well, I've found the solution. You were using an old version of Highmaps, probably 4 or 5. Just update it to +6 and that's all: https://code.highcharts.com/maps/highmaps.js
I just updated code snippet with latest Highmap.js
$(function () {
var data = Highcharts.geojson(Highcharts.maps['countries/us/us-all']),
// Some responsiveness
small = $('#container').width() < 400;
// Set drilldown pointers
$.each(data, function (i) {
this.drilldown = this.properties['hc-key'];
this.value = i; // Non-random bogus data
});
// Instanciate the map
Highcharts.mapChart('container', {
chart: {
events: {
drilldown: function (e) {
if (!e.seriesOptions) {
var chart = this,
mapKey = 'countries/us/' + e.point.drilldown + '-all',
// Handle error, the timeout is cleared on success
fail = setTimeout(function () {
if (!Highcharts.maps[mapKey]) {
chart.showLoading('<i class="icon-frown"></i> Failed loading ' + e.point.name);
fail = setTimeout(function () {
chart.hideLoading();
}, 1000);
}
}, 3000);
// Show the spinner
chart.showLoading('<i class="icon-spinner icon-spin icon-3x"></i>'); // Font Awesome spinner
// Load the drilldown map
$.getScript('https://code.highcharts.com/mapdata/' + mapKey + '.js', function () {
data = Highcharts.geojson(Highcharts.maps[mapKey]);
// Set a non-random bogus value
$.each(data, function (i) {
this.value = i;
});
// Hide loading and add series
chart.hideLoading();
clearTimeout(fail);
chart.addSeriesAsDrilldown(e.point, {
name: e.point.name,
data: data,
dataLabels: {
enabled: true,
format: '{point.name}'
}
});
});
}
this.setTitle(null, { text: e.point.name });
},
drillup: function () {
this.setTitle(null, { text: 'USA' });
}
}
},
title: {
text: 'Highcharts Map Drilldown'
},
subtitle: {
text: 'USA',
floating: true,
align: 'right',
y: 50,
style: {
fontSize: '16px'
}
},
legend: small ? {} : {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
colorAxis: {
min: 0,
minColor: '#E6E7E8',
maxColor: '#005645'
},
mapNavigation: {
enabled: true,
buttonOptions: {
verticalAlign: 'bottom'
}
},
plotOptions: {
map: {
states: {
hover: {
color: '#EEDD66'
}
}
}
},
series: [{
data: data,
name: 'USA',
dataLabels: {
enabled: true,
format: '{point.properties.postal-code}'
}
}],
drilldown: {
activeDataLabelStyle: {
color: '#FFFFFF',
textDecoration: 'none',
textOutline: '1px #000000'
},
drillUpButton: {
relativeTo: 'spacingBox',
position: {
x: 0,
y: 60
}
}
}
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/maps/highmaps.js"></script>
<script src="https://code.highcharts.com/maps/modules/data.js"></script>
<script src="https://code.highcharts.com/maps/modules/drilldown.js"></script>
<script src="https://code.highcharts.com/maps/modules/exporting.js"></script>
<script src="https://code.highcharts.com/maps/modules/offline-exporting.js"></script>
<script src="https://code.highcharts.com/mapdata/countries/us/us-all.js"></script>
<div id="container" style="height: 500px; min-width: 310px; max-width: 800px; margin: 0 auto"></div>

Auto-refresh Json data in Highcharts

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
}

Categories