Generating CSS-Only Sparklines in Python

This post was updated on March 21, 2007 to fix broken images and links.

I decided I wanted to figure out a way to display sparklines without using graphics. More specifically, I wanted a way to do it without using the Python imaging library, which is not installed on OS X by default.

That left me with CSS. I slammed my head against that stupid wall for a few hours, then found this: CSS-based sparklines v1.0. That guy does a good job figuring out and providing the CSS, and a nice blood-glucose level example (view source to see the various divs he uses). He uses the top and left CSS parameters to position each pixel-sized dot in the sparkline. What a pain in the ass it’d be to hand-code each of those divs, huh?

Yay, Python.

I wrote a script that will take a Python list of any data and generate all the in-body div statements which use his CSS instructions. It will reduce the range of data to integers between 0 and 10 while maintaining the relativity of it all. Unlike his example, the script calculates only one horizontal line as the mean of the data provided. In cases where the maximum or minimum value occurs more than once, it will highlight only the latest instance of that value. Of course, as with his example, you can change the appearance of the sparkline simply by tweaking the CSS.

As a proof of concept, I ran the hourly temperature readings (°F) in the D.C. area for December 1 through Dec. 3 as reported by Weather Underground. On that page, you’ll see there’s a graph for the temps over this time span, reproduced here:

graph1.gif

Running the data returns a Python list of lines in XHTML:

>>> from cssSparklines import *
>>> a = [37.0, 36.0, 35.1, ... 35.6, 35.1]
>>> b = makeSparkline(a)
>>> b
['<div id="graph" style="height: 10px; ... top: 5px;"></div>', '</div>']

Just drop that into an HTML file linked to the CSS, and bickity-bam.

Update 3/21/2007: Since moving to WordPress, I don’t have control over the site’s CSS (yet), so you can view the output of the Python script here:
http://www.eringary.com/python/sparkline.html

In effort to show how the script will maintain the overall integrity of the data (even though it man-handles it quite a bit), take a look at the same graph from Weather Underground with the temperature graph isolated and condensed down to a similar size:

graph2.gif

View the Python code. If you download it, remember to change the file extension from .txt to .py . Oh, in order for the average line to work, you’ll need to start with my tweaked version of his original CSS.

Advertisements