Smoothie Charts is a simple library for displaying smooth live time lines. This tutorial will get you up and running in 10 minutes...
Copy smoothie.js to your project and include it:
<script type="text/javascript" src="smoothie.js"></script>
<canvas id="mycanvas" width="400" height="100"></canvas>
Use the default settings for now. These can be tweaked later.
var smoothie = new SmoothieChart(); smoothie.streamTo(document.getElementById("mycanvas"));
Each line requires a TimeSeries
object.
For this example, we'll create two TimeSeries
objects and append random data to them every second.
// Data var line1 = new TimeSeries(); var line2 = new TimeSeries(); // Add a random value to each line every second setInterval(function() { line1.append(Date.now(), Math.random()); line2.append(Date.now(), Math.random()); }, 1000); // Add to SmoothieChart smoothie.addTimeSeries(line1); smoothie.addTimeSeries(line2);
In reality, you'd probably want to get data from a WebSocket, rather than random generator.
Important notes:
TimeSeries.append()
takes two parameters: timestamp of the data point, and value of the data point.The above chart shows an issue... we cannot plot a line until the next data point is known. To get around this, we add a delay to the chart, so upcoming values are known before we need to plot the line.
This makes the chart look like a continual stream rather than very jumpy on the right hand side.
To add the delay, we modify the SmoothieChart.streamTo()
call to include the delay.
smoothie.streamTo(document.getElementById("mycanvas"), 1000 /*delay*/);
That's much easier on the eye.
The API provides a few hooks for tweaking the style of the lines and the grid.
var smoothie = new SmoothieChart({ grid: { strokeStyle:'rgb(125, 0, 0)', fillStyle:'rgb(60, 0, 0)', lineWidth: 1, millisPerLine: 250, verticalSections: 6, }, labels: { fillStyle:'rgb(60, 0, 0)' } }); smoothie.addTimeSeries(line1, { strokeStyle:'rgb(0, 255, 0)', fillStyle:'rgba(0, 255, 0, 0.4)', lineWidth:3 }); smoothie.addTimeSeries(line2, { strokeStyle:'rgb(255, 0, 255)', fillStyle:'rgba(255, 0, 255, 0.3)', lineWidth:3 });