I'm working on getting a Highcharts bar chart together dynamically changes with Ajax calls. I think I'm really close to figuring it out but it's not displaying and I'm not seeing the problem. I believe I can update points the way I've done it inside the setInterval function. I'm hoping someone can eyeball it and give me suggestions...thanks a lot
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highcharts Example</title>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
<!--Ajax Function-->
var flag = 1;
var xmlhttp;
var url="http://mysite.com/web/ajax_info.txt";
//ajax call
function loadXMLDoc(url, cfunc){
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url, true);
xmlhttp.send();
}
function myFunction(){
loadXMLDoc(url+'?_dc='+(new Date()).getTime(), function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
flag = 1;
}
});
}
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Active Tribble Sales'
},
subtitle: {
text: 'Source: TribbleInternational.com'
},
xAxis: {
categories: [
'Tribbles'
]
},
yAxis: {
min: 0,
title: {
text: 'Active Sales (%)'
}
},
legend: {
layout: 'vertical',
backgroundColor: '#FFFFFF',
align: 'left',
verticalAlign: 'top',
x: 100,
y: 70,
floating: true,
shadow: true
},
tooltip: {
formatter: function() {
return ''+
this.x +': '+ this.y +' mm';
}
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Good',
data: [80]
}, {
name: 'Bad',
data: [1]
}]
},
function(chart){
setInterval(function() {
myFunction();
if(flag == 1){
var point = chart.series[0].points[0],
var point2 = chart.series[1].points[0],
newVal,
inc = Math.round((Math.random() - .5) * 20);
newVal = point.y + inc;
if (newVal < 0 || newVal > 100) {
newVal = point.y - inc;
}
point.update(newVal);
point2.update(1);
}
else{
var point2 = chart.series[0].points[0],
var point = chart.series[1].points[0],
newVal,
inc = Math.round((Math.random() - .5) * 20);
newVal = point2.y + inc;
if (newVal < 0 || newVal > 100) {
newVal = point2.y - inc;
}
point2.update(newVal);
point.update(1);
}
flag = 0; //reset flag after point update.
}, 3000);
});
});
</script>
</head>
<body>
<script src="highcharts.js"></script>
<div id="container" style="min-width: 300px; max-width: 300px; height: 400px; margin: 0 auto"></div>
</body>
</html>
Check the syntax i.e the braces are closed correctly
as for as i noticed
series: [{
name: 'Good',
data: [80]
}, {
name: 'Bad',
data: [1]
}]
},
should be })
since //
chart = new Highcharts.Chart({
and
}
flag = 0; //reset flag after point update.
}, 3000);
// } is missing
});
});
pls check it
Related
I am trying to use a dynamic chart with my arduino web page. sensor values are updated to the page using ajax. But I can not update the chart with sensor values. sensor values are in variable "data_val".once I call that variable in chart function it wont work. the problem is the value on variable data_val does not go to the chart's y value. but when i assign a numerical value to variable y it shows that assigned value.
I am not familiar with java-script and ajax. so can anyone help me to solve this.
var data_val = 0;
function GetArduinoInputs() {
nocache = "&nocache=" + Math.random() * 1000000;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null) {
document.getElementById("input3").innerHTML =
this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
data_val = this.responseXML.getElementsByTagName('analog')[0].childNodes[0].nodeValue;
document.getElementById("demo").innerHTML = data_val;
}
}
}
}
request.open("GET", "ajax_inputs_one" + nocache, true);
request.send(null);
setTimeout('GetArduinoInputs()', 1000);
}
function gr() {
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 y = data_val;
var x = (new Date()).getTime(); // current time
series.addPoint([x, y], true, 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 += 1) {
data.push({
x: time + i * 1000,
});
}
return data;
}())
}]
});
}
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<body onLoad="gr();GetArduinoInputs()">
<p>Motor Speed: <span id="input3">...</span> Hz</p>
<p id="demo"></p>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
You need to fix your AJAX call to actually get the data. I added a failure else-block to randomly assign a value for updating.
I also changed a few variable and class names.
var currentSpeed = 0, // Current speed
dataFetchRate = 1000, // Rate of data request
refreshRate = dataFetchRate; // Rate of adding the current speed to the chart
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
if (max === undefined) { max = min; min = 0; }
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function GetArduinoInputs() {
var nocache = "&nocache=" + getRandomInt(1000000);
var request = new XMLHttpRequest();
var requestUrl = 'ajax_inputs_one' + nocache;
request.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {
if (this.responseXML != null) {
var rawData = this.responseXML.getElementsByTagName('analog')[0]
.childNodes[0].nodeValue;
currentSpeed = parseInt(rawData, 10);
}
} else {
currentSpeed = getRandomInt(144); // If error, get a random number from 0 - 144
}
document.getElementById('current-speed').innerHTML = currentSpeed;
}
}
request.open('GET', requestUrl, true);
request.send(null);
setTimeout(GetArduinoInputs, dataFetchRate);
}
function gr() {
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 y = currentSpeed;
var x = (new Date()).getTime(); // current time
series.addPoint([x, y], true, true);
}, refreshRate);
}
}
},
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 += 1) {
data.push({
x: time + i * 1000,
});
}
return data;
}())
}]
});
}
#container {
min-width: 310px;
height: 400px;
margin: 0 auto;
}
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<body onLoad="gr();GetArduinoInputs()">
<p>Motor Speed: <span id="current-speed">...</span> Hz</p>
<div id="container"></div>
</body>
Complete beginner here.
From Spline updating each second, I wanna change amplitude of graph (it means, the range of random generated number) via slider. How to implement it?
I am able to change variables, but variable y that stands for amplitude is inside a function, and none of my solutions worked unfortunately.
Here is the code
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
<script>
$(document).ready(function () {
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 = Math.random();
series.addPoint([x, y], true, 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 += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
</script>
</body>
How to add slider, that can control value of variable y in load?
Thanks in advance.
Refer to this live demo: http://jsfiddle.net/kkulig/4y120nbo/
I placed the reference to the HTML slider in 'higher' scope than load function. I use rangeForm.value to manipulate the amplitude of generated numbers:
// 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() * rangeForm.value;
series.addPoint([x, y], true, true);
}, 1000);
With the Highcharts value-in-legend plugin http://www.highcharts.com/plugin-registry/single/10/Value-In-Legend, I have been able to kind of implement a sort of multiple series total, but I do not understand how to get a total for a clicked y-axis point.
For example when I click, one day I will get the 3 separate series numbers, but I would like to get a total somehow as well, but I only know the y points on load and the visible y-points on redraw. I think the difficulty is getting the total of the 3 series points versus getting the individual point's value.
$(function() {
// Start the standard Highcharts setup
var seriesOptions = [],
yAxisOptions = [],
seriesCounter = 0,
names = ['MSFT', 'AAPL', 'GOOG'],
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
};
// 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() {
$('#container').highcharts('StockChart', {
chart: {
events: {
load: function(event) {
console.log('load');
var total = 0;
for(var i = 0, len = this.series[0].yData.length; i < len; i++) {
total += this.series[0].yData[i];
}
totalText_posts = this.renderer.text('Total: ' + total, this.plotLeft, this.plotTop - 35).attr({
zIndex: 5
}).add()
},
redraw: function(chart) {
console.log('redraw');
console.log(totalText_posts);
var total = 0;
for(var i = 0, len = this.series[0].yData.length; i < len; i++) {
if(this.series[0].points[i] && this.series[0].points[i].visible) total += this.series[0].yData[i];
}
totalText_posts.element.innerHTML = 'Total: ' + total;
}
}
},
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function() {
return(this.value > 0 ? '+' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
legend: {
enabled: true,
floating: true,
align: 'left',
verticalAlign: 'top',
y: 35,
labelFormat: '<span style="color:{color}">{name}</span>: <b>{point.y:.2f} USD</b> ({point.change:.2f}%)<br/>',
borderWidth: 0
},
plotOptions: {
series: {
compare: 'percent',
cursor: 'pointer',
point: {
events: {
click: function () {
alert('Category: ' + this.category + ', value: ' + this.y);
}
}
}
}
},
series: seriesOptions
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.src.js"></script>
<script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://rawgithub.com/highslide-software/value-in-legend/master/value-in-legend.js"></script>
<div id="container" style="height: 400px; min-width: 500px"></div>
I was able to find out a way to put the total result as a title in a multi series by reading the source code for the Highcharts value-in-legend plugin https://rawgithub.com/highslide-software/value-in-legend/master/value-in-legend.js.
$(function () {
var seriesOptions_likes = [],
seriesCounter_likes = 0,
names_likes = ['MSFT', 'AAPL', 'GOOG'],
totalText_likes = 0;
/**
* Create the chart when all data is loaded
* #returns {undefined}
*/
function createLikesChart() {
Highcharts.stockChart('container_likes', {
chart: {
},
rangeSelector: {
selected: 4
},
title: {
text: 'Total Results: '
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? ' + ' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent',
showInNavigator: true
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2,
split: true
},
series: seriesOptions_likes,
legend: {
enabled: true,
floating: true,
align: 'left',
verticalAlign: 'top',
y: 65,
borderWidth: 0
},
});
}
$.each(names_likes, function (i, name) {
$.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=' + name.toLowerCase() + '-c.json&callback=?', function (data) {
seriesOptions_likes[i] = {
name: name,
data: data
};
// 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_likes += 1;
if (seriesCounter_likes === names_likes.length) {
createLikesChart();
}
});
});
});
(function (H) {
H.Series.prototype.point = {}; // The active point
H.Chart.prototype.callbacks.push(function (chart) {
$(chart.container).bind('mousemove', function () {
var legendOptions = chart.legend.options,
hoverPoints = chart.hoverPoints,
total = 0;
if (!hoverPoints && chart.hoverPoint) {
hoverPoints = [chart.hoverPoint];
}
if (hoverPoints) {
var total = 0,
ctr = 0;
H.each(hoverPoints, function (point) {
point.series.point = point;
total += point.y;
});
H.each(chart.legend.allItems, function (item) {
item.legendItem.attr({
text: legendOptions.labelFormat ?
H.format(legendOptions.labelFormat, item) :
legendOptions.labelFormatter.call(item)
});
});
chart.legend.render();
chart.title.update({ text: 'Total Results: ' + total.toFixed(2) });
}
});
});
// Hide the tooltip but allow the crosshair
H.Tooltip.prototype.defaultFormatter = function () { return false; };
}(Highcharts));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<div id="container_likes" style="height: 400px; min-width: 600px"></div>
I'm using Highcharts to draw a graph with dynamic data.
I found this official demo.http://jsfiddle.net/vn9bk80j/
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#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);
}, 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: []
}]
});
});
});
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
The graph window size is varing, it looks like
Howerver, I need graph window size to be fixed, data in this graph shifts from right to left as a whole from the beginning. Just like in the following pic.
How can I get the effects in picture 2 with Highcharts?
You can use null points to create empty space, and then just add pints with shift=true, see: http://jsfiddle.net/vn9bk80j/1/
function getEmptyData() {
var interval = 1000, // 1 second,
numberOfPoints = 50,
now = (new Date()).getTime(),
min = now - interval * numberOfPoints,
points = [];
while (min <= now) {
points.push([min, null]); // set null points
min += interval;
}
return points;
}
And method use case:
series: [{
name: 'Random data',
data: getEmptyData()
}]
shift=true example:
series.addPoint([x, y], true, true);
I am new on highchart. I have gone through the help portal of this and I am unable to fulfill my requirement so need you help/guide to complete this task .
My task is to read the data from a csv/TXT file which contains TPS details as per below format and show it on a dynamic running chart ( it's ok if the chart will refresh in one minute ) .
DATA format:
16:08:02,3
16:08:04,5
16:08:05,1
16:09:01,10
The above file is appending on every second , will read the last one minute data from file and plot this on chart .
I have tried this using below code. Don't know what I am missing.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>TPS Example</title>
<script type="text/javascript" src="C:/Backup/SUNIL/Software/library/jquery-2.2.0.js"></script>
<style type="text/css">
${demo.css}
</style>
<script type="text/javascript">
$(function () {
$(document).ready(function () {
Highcharts.setOptions({
global: {
useUTC: false
}
});
$('#container').highcharts({
chart: {
renderTo: 'container',
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, true);
}, 1000);
}
}
},
title: {
text: 'TPS Data'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150
},
yAxis: {
title: {
text: 'Value'
},
plotLines: [{
value: 3,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function () {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.dateFormat('%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 += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
});
});
});
</script>
</head>
<body>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<div id="container" style="min-width: 50px; height: 200px; margin: 0 auto"></div>
</body>
</html>
You probably have incorrect paths to your script files.
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
<script src="C:\Backup\SUNIL\Software\library\Highcharts-4.2.1\js\highcharts.js"></script>
The code works fine: http://jsfiddle.net/tmp3pty2/