This post originated from an RSS feed registered with Python Buzz
by Thomas Guest.
Original Post: Scatter pictures with Google Charts
Feed Title: Word Aligned: Category Python
Feed URL: http://feeds.feedburner.com/WordAlignedCategoryPython
Feed Description: Dynamic languages in general. Python in particular. The adventures of a space sensitive programmer.
I almost wanted to call this post “Stupid Google Tricks” :-) What fun diagrams can you imagine making with the Google Charts Service?
Here’s a stupid trick: you can use the Python Imaging Library to convert a picture into a URL which Google charts will render as the original picture.
Here’s the original picture:
here’s the version served up by Google charts:
here’s the code:
import Image
import string
def scatter_pixels(img_file):
"""Return the URL of a scatter plot of the supplied image
The image will be rendered square and black on white. Adapt the
code if you want something else.
"""
# Use simple chart encoding and to make things really simple
# use one pixel per encode value
simple = string.uppercase + string.lowercase + string.digits
rsimple = simple[::-1]
w = len(simple)
W = w * 3
img = Image.open(img_file).resize((w, w)).convert("1")
pels = img.load()
black_pels = [(x, y) for x in range(w) for y in range(w)
if pels[x, y] == 0]
xs = "".join(simple[x] for x, _ in black_pels)
ys = "".join(rsimple[y] for _, y in black_pels)
sqside = 3.0
return (
"http://chart.apis.google.com/chart?"
"cht=s&" # Draw a scatter graph
"chd=s:%(xs)s,%(ys)s&" # using simple encoding and
"chm=s,000000,1,2.0,%(sqside)r,0&"# square black markers
"chs=%(W)rx%(W)r" # at this size.
) % locals()