This week’s assignment involved creating an application that we could use for our final project. As I’m building a PM 2.5 sensor, I decided to build the live temperature / pollution concentration level chart that would be regularly updated online.
I decided to look online to see what sorts of libraries already existed that did the plotting for me. I knew about D3.js, but it didn’t seem to be easy to support live plotting. However, I found Canvas.js supported live charts with some very nice functionality. I would be able to use a set of these charts that interacted with a simple Python server to pull data and still look very presentable. Here’s an example of a live chart that is randomly generating data to plot:
This is the code that is being used to generate the chart:
<head>
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Live Temperature Data"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 100;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
<script type="text/javascript" src="http://fab.cba.mit.edu/classes/MAS.863/section.EECS/people/Jain/js/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
The code right now just generats random values on the line yVal = yVal + Math.round(5 + Math.random() *(-5-5));
but this could be switched to be an AJAX request to the server that would then return the data we would be looking for, and we could push that onto dps
so that it keeps having the new data as it comes in.