How to display two dynamic spline charts on one page? - javascript

I just learned about creating dynamic charts using highcharts. I need help, i'm trying to make a dynamic spline chart with data from php like this (number 2). Then I try to create a dynamic spline chart under it (different div) by varying the data in php. But the results only show the chart below (chart B), on chart A does not display data as before B chart added. I asked, how to make two dynamic spline charts on one page? thank you
This is the code that I use
<?php //PHP for Chart A
// Set the JSON header
header("Content-type: text/json");
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = rand(0, 100);
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
<?php //PHP for Chart B
// Set the JSON header
header("Content-type: text/json");
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = rand(100, 200);
// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>
this is javascript code:
//JS of Chart A
var chart;
function requestData() {
$.ajax({
url: 'dataChartA.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
document.addEventListener('DOMContentLoaded', function() {
chart = Highcharts.chart('chartA', {
chart: {
type: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Chart A'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Chart A',
data: []
}]
});
});
//JS for Chart B
var chart;
function requestData() {
$.ajax({
url: 'dataChartB.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 20; // shift if the series is
// longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 1000);
},
cache: false
});
}
document.addEventListener('DOMContentLoaded', function() {
chart = Highcharts.chart('chartB', {
chart: {
type: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Chart B'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value B',
margin: 80
}
},
series: [{
name: 'Chart B',
data: []
}]
});
});
</head>
<body>
<div id="chartA"></div>
<div id="chartB"></div>
</body>
Results in the browser : https://imgur.com/kAVGQUk

Related

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

Plot graph points as a live stream : Highcharts

So What I have is a graph which updates particular points as once. But the problem is that the graph is not being plotted as a live stream. it just plots points at once
Here is the Code:
var chart;
function requestData() {
$.ajax({
url: 'https://api.myjson.com/bins/wmxsn',
success: function(data) {
var series = chart.series[0],
shift = series.data.length > 20, // shift if the series is
y = data;
data.forEach(function(el) {
chart.series[0].addPoint(el, false, shift);
});
chart.redraw();
setTimeout(requestData, 1000);
},
cache: false
});
}
document.addEventListener('DOMContentLoaded', function() {
chart = Highcharts.chart('container', {
chart: {
type: 'line',
events: {
load: requestData
}
},
title: {
text: 'Live random data'
},
xAxis: {
crosshair: false
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'Value',
margin: 80
}
},
series: [{
name: 'Random data',
data: []
}]
});
});
Here's the Fiddle Example of how data points are plotting.
http://jsfiddle.net/abnitchauhan/g86tbydj/
But what I want is the flow to be smooth as like the following example:
(It's just an example of how the data should flow irrespective of the code. Please only see the graph animation in the following code)
https://codepen.io/AbnitChauhan/pen/BaBxyMV
The problem is that you are fetching data, add points and redraw the chart when all points are added. To make it "live" and smooth add points separately in the equal interval. If the interval is very small disable the animation which makes it work better (chart.animation = false). Check demos posted below.
Example code:
function requestData() {
$.ajax({
url: 'https://api.myjson.com/bins/wmxsn',
success: function(data) {
var series = chart.series[0],
shift = series.data.length > 200, // shift if the series is
y = data,
i = 0;
var interval = setInterval(function () {
if (i < 10) {
chart.series[0].addPoint(data[i] * Math.random() * 10, true, shift);
i++
} else {
clearInterval(interval);
requestData();
}
}, 30);
},
cache: false
});
}
Demo:
http://jsfiddle.net/BlackLabel/cuxr865g/
http://jsfiddle.net/BlackLabel/jdvm4u2o/
API reference:
https://api.highcharts.com/highcharts/chart.animation

Highcharts : Real time updating spline chart sets y-axis data to zero

I am trying to display a set of dynamic data in a spline type chart using highcharts.
My spline type line chart has 4 series of data that needs to update through a service call. Service returns an array of data such as [0.345, 0.465, 0, 0.453] and I want to update y value of each series with the respective value in the array.
But my chart does not draw the data as expected. Even if I receive different values for y, in the chart it always displays it as 0.
This is my source code. Greatly appreciate if someone could help me figure out the issue in this or a give solution to this problem.
function drawHighChart() {
hchart = Highcharts.chart('container', {
chart: {
type: 'spline',
animation: Highcharts.svg,
marginRight: 10,
},
time: {
useUTC: false
},
title: {
text: 'Audio Analytics'
},
xAxis: {
tickInterval: 1,
},
yAxis: {
title: {
text: 'Prediction'
},
min: 0,
max: 1,
tickInterval: 0.5,
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
headerFormat: '<b>{series.name}</b><br/>',
pointFormat: '{point.x:%Y-%m-%d %H:%M:%S}<br/>{point.y:.2f}'
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
/* Initially I'm setting some hardcoded values for each series.*/
series: [{
name: 'Calm',
data: [0.43934, 0.52503, 0.57177, 0.69658, 0.97031, 0.119931, 0.137133]
}, {
name: 'Happy',
data: [0.24916, 0.24064, 0.29742, 0.0000, 0.32490, 0.0000, 0.38121]
}, {
name: 'Angry',
data: [0.11744, 0.17722, 0.16005, 0.19771, 0.20185, 0.24377, 0.32147]
}, {
name: 'Disgust',
data: [0.7988, 0.15112, null, 0.22452, 0.34400, null, 0.34227]
}],
});
}
Now when I call drawHighChart() at the windows onload this is what it outputs.
Now from here, I need to update each series dynamically as service returns a data array.
This is my function that updates the chart dynamically every time the service returns a response. Every time I call this fucntion, I pass a data array constructed from the response data.
initiVal = 7; //This is a gloabl variable that increases x-axis value from 7.
function updateHighChart(dataArray) {
var series = hchart.series[0];
var series1 = hchart.series[1];
var series2 = hchart.series[2];
var series3 = hchart.series[3];
var x = initiVal;
y = dataArray[0];
y1 = dataArray[1];
y2 = dataArray[2];
y3 = dataArray[3];
console.log("dataArray: " + dataArray);
series.addPoint([x, y], true, true);
series1.addPoint([x, y1], true, true);
series2.addPoint([x, y2], true, true);
series3.addPoint([x, y3], true, true);
initiVal++;
}
But even if data is dynamically assigned to y axis values in each series, they do not update as expected in the chart. This is how the charts looks after the 6th second/instance when data needs to dynamically update in the chart.

how to convert high charts code to nvd3.js

Here is my High Chart code for showing live Bitcoin Charts. I really am a noob at PHP, JavaScript etc, so i really need help in converting this code to nvd3.js
PHP Code:
<?php
// Set the JSON header
header("Content-type: text/json");
function getPrice($url){
$decode = file_get_contents($url);
return json_decode($decode, true);
}
$btce = getPrice('https://btc-e.com/api/2/btc_usd/ticker');
$btcePrice = round($btce["ticker"]["last"], 2);
// The x value is the current JavaScript time, which is the Unix time multiplied
// by 1000.
$x = time() * 1000;
// The y value is a random number
// Create a PHP array and echo it as JSON
$ret = array($x, $btcePrice);
echo json_encode($ret);
?>
HTML and Javascript Code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<script type="text/javascript">
var chart; // global
/**
* Request data from the server, add it to the graph and set a timeout
* to request again
*/
function requestData() {
$.ajax({
url: 'x.php',
success: function(point) {
var series = chart.series[0],
shift = series.data.length > 175; // shift if the series is longer than 20
// add the point
chart.series[0].addPoint(point, true, shift);
// call it again after one second
setTimeout(requestData, 3000);
},
cache: false
});
}
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: requestData
}
},
title: {
text: 'Average price chart'
},
xAxis: {
type: 'datetime',
tickPixelInterval: 150,
maxZoom: 20 * 1000
},
yAxis: {
minPadding: 0.2,
maxPadding: 0.2,
title: {
text: 'USD',
margin: 80
}
},
series: [{
name: 'Live BTC USD Chart',
data: []
}]
});
});
</script>
<div id="container" style="width:100%; height:400px;"></div>
</body>
</html>
any help in explaining how to convert this code to work with nvd3.js would be greatly appreciated
Thanks!

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.

Categories

Resources