Skip to content

Instantly share code, notes, and snippets.

@drewyeaton
Created December 23, 2011 02:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drewyeaton/1512866 to your computer and use it in GitHub Desktop.
Save drewyeaton/1512866 to your computer and use it in GitHub Desktop.
Simple Sparklines as Data URI
# Sparkline code from Joe Gregorio (http://bitworking.org/news/Sparklines_in_data_URIs_in_Python)
from PIL import Image, ImageDraw
import StringIO
import urllib
def plot_sparkline(results):
"""Returns a sparkline image as a data: URI.
The source data is a list of values between
0 and 100. Values greater than 95
are displayed in red, otherwise they are displayed
in green"""
im = Image.new("RGB", (len(results)*2, 15), 'white')
draw = ImageDraw.Draw(im)
for (r, i) in zip(results, range(0, len(results)*2, 2)):
color = (r > 50) and "red" or "gray"
draw.line((i, im.size[1]-r/10-4, i, (im.size[1]-r/10)), fill=color)
del draw
f = StringIO.StringIO()
im.save(f, "PNG")
return 'data:image/png,' + urllib.quote(f.getvalue())
if __name__ == "__main__":
import random
html = """
<html>
<body>
<p>Does my sparkline
<img src="%s">
fit in a nice paragraph of text?
</p>
</body>
</html>"""
print html % plot_sparkline([random.randint(0, 100) for i in range(30)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment