JavaScript Dynamic / Live Multi Series Chart - 0 | JSFiddle Sample Code
JavaScript Dynamic / Live Multi Series Chart - 0 | JSFiddle Sample Code
by Nayana Das
HTML
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div style="margin-top:16px;color:dimgrey;font-size:9px;font-family: Verdana, Arial, Helvetica, sans-serif;text-decoration:none;">Source: <a href="https://canvasjs.com/javascript-charts/dynamic-live-multi-series-chart/" target="_blank" title="JavaScript Dynamic / Live Multi Series Chart ">https://canvasjs.com/javascript-charts/dynamic-live-multi-series-chart/</a></div>
JavaScript
window.onload = function () {
var dataPoints1 = [];
var dataPoints2 = [];
var chart = new CanvasJS.Chart("chartContainer", {
zoomEnabled: true,
title: {
text: "Share Value of Two Companies"
},
axisX: {
title: "chart updates every 3 secs"
},
axisY:{
prefix: "$"
},
toolTip: {
shared: true
},
legend: {
cursor:"pointer",
verticalAlign: "top",
fontSize: 22,
fontColor: "dimGrey",
itemclick : toggleDataSeries
},
data: [{
type: "line",
xValueType: "dateTime",
yValueFormatString: "$####.00",
xValueFormatString: "hh:mm:ss TT",
showInLegend: true,
name: "Company A",
dataPoints: dataPoints1
},
{
type: "line",
xValueType: "dateTime",
yValueFormatString: "$####.00",
showInLegend: true,
name: "Company B" ,
dataPoints: dataPoints2
}]
});
function toggleDataSeries(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
}
else {
e.dataSeries.visible = true;
}
chart.render();
}
var updateInterval = 3000;
// initial value
var yValue1 = 600;
var yValue2 = 605;
var time = new Date;
// starting at 9.30 am
time.setFullYear(2020, 0, 08);
time.setHours(9);
time.setMinutes(30);
time.setSeconds(00);
time.setMilliseconds(00);
function updateChart(count) {
count = count || 1;
var deltaY1, deltaY2;
for (var i = 0; i < count; i++) {
time.setFullYear(2020, 0, 12);
time.setHours(12);
time.setMinutes(30);
time.setSeconds(00);
time.setMilliseconds(00);
time.setTime(time.getTime()+ updateInterval);
deltaY1 = .5 + Math.random() *(-.5-.5);
deltaY2 = .5 + Math.random() *(-.5-.5);
// adding random value and rounding it to two digits.
yValue1 = Math.round((yValue1 + deltaY1)*100)/100;
yValue2 = Math.round((yValue2 + deltaY2)*100)/100;
// pushing the new values
dataPoints1.push({
x: time.getTime(),
y: yValue1
});
dataPoints2.push({
x: time.getTime(),
y: yValue2
});
}
// updating legend text with updated with y Value...