Web graph producing library
Fredrik Lundh
fredrik at pythonware.com
Thu May 1 08:02:42 EDT 2003
"VanL" <vlindberg at verio.net> wrote:
> I have googled around for this, and I can't find it.
>
> I have a web app that produces some reports. I would like to produce
> some reports in graph form, as well. I have found a couple interfaces
> to various image libraries, but none that are particularly specialized
> for graphs.
>
> For example I would love to have something like this:
>
> import webgraph
>
> data = {'adam': (30, 'yellow'),
> 'jeff': (40, 'green'),
> 'rob': (10, 'red'),
> 'bill': (2, 'purple'),
> 'bob': (15, 'black'),
> 'uneaten': (3, 'white')
> }
> title = "Apples eaten by team member"
>
> piechart = webgraph.PieChart(data, title=title)
>
> piechart.dump() # Dumps pie graph in png (or other) format
here's the first part of your webgraph library:
# requires PIL 1.1.4
from PIL import Image, ImageDraw, ImageFont
# path to nice truetype font
FONTFILE = "arial.ttf"
def PieChart(data, title=None, size=400):
items = data.items()
items.sort()
im = Image.new("P", (size+200, size+50))
draw = ImageDraw.Draw(im)
draw.rectangle((0, 0) + im.size, fill="white")
bbox = (10, 50+10, size-20, size+50-20)
angle = 0
x = size + 20
y = 50
font = ImageFont.truetype(FONTFILE, 10)
total = 0
for name, (value, color) in items:
total = total + value
for name, (value, color) in items:
slice = 360.0 * value / total
draw.pieslice(bbox, angle, angle + slice, fill=color, outline="black")
angle = angle + slice
draw.rectangle((x, y, x+10, y+10), fill=color, outline="black")
draw.text((x + 15, y), name, font=font, fill="black")
y = y + 12
if title:
font = ImageFont.truetype(ARIAL, 20)
draw.text((10, 10), title, font=font, fill="black")
return im
#
# usage:
piechart = PieChart(data, title=title)
piechart.save("out.png")
# or piechart.save(sys.stdout. "PNG")
for more info about PIL, see:
http://www.pythonware.com/products/pil/
http://effbot.org/zone/pil-index.htm
http://effbot.org/zone/pil-changes-114.htm
</F>
More information about the Python-list
mailing list