Sparklines in Javascript With Sparklines.js

June 26, 2008. Filed under javascript 18 processing-js 9 sparklines-js 3

Earlier this week I spent a couple of days playing with the idea of sparklines, and ended up making a JavaScript library for generating sparklines in the canvas element. Because I've been using it a bit recently, I used Processing.js to handle the visualization.


The site has about a dozen different examples of how you can combine and create different configurations for sparklines, but I'll do a quick rundown here.

  1. Can create bar or line sparklines.
  2. Can clearly demarcate percentiles (where 0.25 is Q1, 0.5 is the median, and so on, but you can also chose to indicate arbitrary percentiles instead).
  3. Can clearly demarcate arbitrary values (perhaps wanting to show lines at 70 and 80 to emphasize the number of students receiving a C on an exam).
  4. Can fill in the background between two lines, further emphasizing the range between them.
  5. Can configure padding around edges, all colors, space between bars on bar graph, etc.
  6. Designed to work with arbitrary datatypes, where you write a function to extract heights from it.
  7. Adapts to the height and width of the canvas it is given: you can shrink them down or blow them up, and they'll do their best to display their data.

(Sorry that the examples below are actually jpg's from screenshots of the canvases instead of the actual canvases themselves, you can see the real thing on the project page. My blog setup, which I've just gotten a few ideas about improving now, isn't completely intuitive for including raw markup.)

Example of a Bar Sparkline

A bar sparkline created with Sparklines.js

This is one of my favorite bar sparklines.

var data3 =[120,130,80,100,90,105,95,60,70,75,
var opts = {'percentage_lines':[0.25,0.75],"fill_between_percentage_lines":true,
new Sparkline('bar4', data3).draw();

Example of a Line Sparkline

A line sparkline created with Sparklines.js

This is a line sparkline, with filled in space between lines at the absolute values of 90 and 110, as well as lines at the 25th and 75th percentiles.

var data3 = [120,130,80,100,90,105,95,60,70,75,
var opts ={"value_lines":[90,110],"top_padding":5,
new Sparkline('simple10', data3, opts).draw();

There are a number more examples, and instructions at the project page. Let me know if you have any feedback!