Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Create a sparkline chart, render to .png, embed into a line of text as a data: URI
<html>
<head>
<style>
p {width: 20em;}
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Does my
sparkline <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAAAPAgMAAADFfETiAAAADFBMVEX/////AACAbIAAAAAe6DapAAAAWUlEQVR42m3OKw7AQAgE0BEVc6wVK3osRAXH7vBZUlHEwEsgAQtZu/LCjyPCdkyZYzt27AfLfGwyZF+GtE7Sd9llKp3RybZZTGO2tacnSIzZzvga5a5yNOAFUsco8dm3E2wAAAAASUVORK5CYII="> fit in a nice paragraph of text? Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.</p>
</body>
</html>
"""
An experiment to embed a sparkline-style mini chart into a line of text as a
data: URI.
Wed, 25 Apr 2007
"""
import StringIO
import urllib
import base64
import zlib
import Image, ImageDraw, PngImagePlugin
def mychunk(fp, sid, *data):
if sid == "PLTE":
pal = data[0]
n = len(pal)
while pal[n-6:n] == '\x00\x00\x00\x00\x00\x00':
n = n - 3
data = (pal[:n],)
PngImagePlugin.putchunk(fp, sid, *data)
def myPngSave(im, fp, filename):
PngImagePlugin._save(im, fp, filename, chunk=mychunk)
Image.register_save("PNG", myPngSave)
def plot_sparkline(results, threshold=75, height=15):
"""Returns a sparkline image as a data: URI.
The source data is a list of values between 0 and 100.
Values greater than (threshold) are displayed in red,
otherwise they are displayed in gray"""
width = len(results)*2
colors = [
('white', (255,255,255)),
('red', (255,000,000)),
('grey', (128,108,128)),
]
palette = [0]*3*256 # empty palette
colornames = list()
colorindex = dict()
for i, (name, val) in enumerate(colors):
colornames.append(name)
colorindex[name] = i
palette[i*3:i*3+3] = list(val)
im = Image.new("P", (width, height), colorindex['white'])
im.putpalette(palette)
draw = ImageDraw.Draw(im)
for (i, r) in enumerate(results):
color = (r > threshold) and colorindex['red'] or colorindex['grey']
draw.line((i*2, (height-(height/3))*(100-r)/100, i*2,
(height-(height/3))*(100-r)/100+(height/3)), fill=color)
del draw
f = StringIO.StringIO()
im.save(f, "PNG", optimize=1, bits=2)
#im.save(open("sparkline.png","w"), "PNG", optimize=1, bits=2)
return 'data:image/png;base64,' + base64.b64encode(f.getvalue())
if __name__ == "__main__":
import random
html = """
<html>
<head>
<style>
p {width: 20em;}
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Does my
sparkline <img src="%s"> fit in a nice paragraph of text? Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat.</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