Created
December 23, 2011 02:39
-
-
Save drewyeaton/1512866 to your computer and use it in GitHub Desktop.
Simple Sparklines as Data URI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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