Graph Library

This is a very simple, lightweight graph library (graph (About Modules)) for displays that use Espruino's Graphics library.

In it's simplest form, you just call drawLine or drawBar with the Graphics instance as the first argument and the data as the second:

var data = [0,1,3,8,10,12,12,10,8,3,1,0];
require("graph").drawLine(g, data);
// Remember to call `g.flip()` to update your display if needed

By default the data is auto-scaled to fit the screen:

graph

But there are other options you can supply via an object as the third argument:

For example:

var data = [0,1,3,8,10,12,12,10,8,3,1,0];
require("graph").drawLine(g, data, {
  miny: 0,
  axes : true,
  gridy : 5,
  xlabel : null
});

Draws a graph with axes, auto-scaled to the nearest 5 points and labelled:

line graph

var data = [1,3,8,10,12,10,8,3,1];
g.clear();
require("graph").drawBar(g, data, {
  miny: 0,
  axes : true,
  gridx : 1,
  gridy : 5
});

Draws a bar graph with labels on both axes:

bar graph

The drawLine/drawBar functions also return an object, containing:

{
  x,    // top left corner of the graph x coordinate
  y,    // top left corner of the graph y coordinate
  w,    // graph width
  h,    // graph height
  getx, // function which given graph data x, returns a x coordinate
  gety, // function which given graph data y, returns a y coordinate
}

And you can also use just drawAxes with the same arguments to draw axes and return the object above.

Example

To display a graph of the last 64 temperature readings from Espruino, taken every 2 seconds you could do something like the following:

var history = new Float32Array(64);

function onTimer() {
  // quickly move all elements of history back one
  history.set(new Float32Array(history.buffer,4));
  // add new history element at the end
  var temp = E.getTemperature();
  history[history.length-1] = temp;
  //
  g.clear();
  // Draw Graph
  var r = require("graph").drawLine(g, history, {
    miny: 0,
    axes : true,
    gridy : 10,
    title: "Temperature"
  });
  // Label last reading
  g.setFontAlign(1,-1);
  g.drawString(Math.round(temp), r.x+r.w, r.gety(temp)+2);
  // Update the screen
  g.flip();
}

// Update temperature every 2 seconds
setInterval(onTimer,2000);
// Update temperature immediately
onTimer();

graph

The code above will work as-is on Pixl.js.

This page is auto-generated from GitHub. If you see any mistakes or have suggestions, please let us know.