User:H2g2bob/pie

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search

License[edit]

Copyright (c) 2009 David Batley (h2g2bob)
MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pie.py[edit]

__all__=["ring_chart", "Series", "AutoColorSeries"]
import math

empty_svg_file = u'''<?xml version="1.0" standalone="no" ?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd">
<svg width="%(width)d" height="%(height)d">
%(content)s
</svg>'''


class Series(object):
	def __init__(self, data_and_opts):
		data_and_opts = list(data_and_opts)
		self.options = []
		self.angles = []
		data_and_opts = [(float(v), o) for (v, o) in data_and_opts]
		total = sum(v for (v, o) in data_and_opts)
		t = 0
		for (v, o) in data_and_opts:
			self.angles.append((math.pi * 2.0 * t) / total)
			t += v
			self.options.append(o)
	def getangle(self, i):
		return self.angles[i]
	def getoptions(self, i):
		return self.options[i]
	@property
	def size(self):
		return len(self.angles)


class AutoColorSeries(Series):
	colors = ["red", "blue", "green", "yellow", "pink", "navy", "cyan", "orange", "lime", "white"]
	def __init__(self, values):
		def _colors():
			while True:
				for color in self.colors:
					yield color
		Series.__init__(self, zip(values, (dict(color=c) for c in _colors())))

		
def ring_chart(data, size=400, margin=0, hole=75):
	originx = originy = float(size) / 2.0
	
	r_outer = (float(size) / 2.0) - margin
	r_inner = float(hole)
	r_one_ring = (r_outer - r_inner) / len(data)
	
	assert r_inner > 0
	assert r_outer > r_inner
	
	return empty_svg_file % {
		"height"  : size,
		"width"   : size,
		"content" : u"\n".join(
			one_ring(
				series,
				originx, originy,
				r_inner + (i * r_one_ring),
				r_inner + ((i+1) * r_one_ring))
			for (i, series) in enumerate(data)
			),
		}

def one_ring(series, originx, originy, r1, r2):
	return u"\n".join(
		segment_path(
			series.getangle(i),
			series.getangle((i+1)%series.size),
			originx, originy,
			r1, r2,
			**series.getoptions(i))
		for i in xrange(series.size)
		)

def segment_path(angle1, angle2, ox, oy, r1, r2, color="red", linecolor="black"):
	"""
	b|\
	 | \
	a\  \
	 d\__\c
	"""
	ay = oy - r2 * math.cos(angle1)
	ax = ox + r2 * math.sin(angle1)
	by = oy - r1 * math.cos(angle1)
	bx = ox + r1 * math.sin(angle1)
	cy = oy - r1 * math.cos(angle2)
	cx = ox + r1 * math.sin(angle2)
	dy = oy - r2 * math.cos(angle2)
	dx = ox + r2 * math.sin(angle2)
	# large arc flag
	if (angle2 - angle1) % (2 * math.pi) > math.pi:
		larc = 1
	else:
		larc = 0
	
	return u"""<path d="M%(ax)f,%(ay)s L%(bx)f,%(by)f A%(r1)f,%(r1)f 0 %(larc)d,1 %(cx)f,%(cy)f L%(dx)f,%(dy)f A%(r2)f,%(r2)f 0 %(larc)d,0 %(ax)f,%(ay)f z"
	style="fill: %(color)s;
		fill-opacity: 1;
		stroke: %(linecolor)s;
		stroke-width: 1"/>""" % locals()

if __name__=='__main__':
	import random
	print ring_chart([
		AutoColorSeries([2, 2, 2]),
		AutoColorSeries([3, 2, 1]),
		AutoColorSeries(sorted((random.random() for x in xrange(10)), reverse=True)),
		])

Electiondata.py[edit]

# -*- coding: utf-8 -*-

import pie
import csv


colors = {
	"Others"            : "#777777",
	"Speaker"           : "white",
	"Labour"            : "#DC241F",
	"Conservative"      : "#0087DC",
	"Liberal Democrat"  : "#FFD700",
	"SNP"               : "#FFFF00",
	"UK Independence"   : "#993366",
	"Ulster Unionist"   : "#9999FF",
	"Plaid Cymru"       : "#FDE60F",
	"Democratic Unionist" : "#D46A4C",
	"Sinn F\xc3\xa9in"  : "#008800",
	"Social Democratic and Labour" : "#99FF66",
	"Green"             : "#99CC33",
	"Independent"       : "#DDDDDD",
	"Scottish Socialist"     : "#FF0000",
	"Socialist Alliance"       : "red",
	"Socialist Labour" : "#780A1F",
	"British National"      : "#000080",
	"Alliance" : "gold",
	"Health Concern"   : "white",
	"Liberal"  : "#FF7300",
	"UK Unionist" : "dimgray",
	"prolife"  : "#333333",
	"cannabis" : "#669966",
	"justice"  : "#7FFFD4",
	"loony"    : "hotpink",
	"Ulster Popular Unionist" : "#FFDEAD",
	"SDP-Liberal Alliance" : "#FFD700",
	"Vanguard" : "darkorange",
	"Independent Republican" : "#00FF00",
	"Respect" : "#FF3300",
	"Referendum Party" : "#E6E6FA",
	"Independent Labour" : "#FFE8E8",
	"Democratic Labour" : "#FF6600",
	"Unity" : "olive",
	"Protestant Unionist" : "#D46A4C",
	"Republican Labour" : "#85DE59",
	"Independent Conservative" : "#DDEEFF",
	"National Liberal" : "#AFEEEE",
	"Ind. Nationalist" : "#99FF66",
	"Irish Labour" : "#CC0000",
	}

def from_csv_file(fname):
	votes_info = []
	seats_info = []
	parties_info = []
	for (party, seats, vote) in csv.reader(open(fname, "r")):
		votes_info.append(vote)
		seats_info.append(seats)
		parties_info.append(party.strip())
	return pie.ring_chart([
		pie.Series((v, dict(color=colors[p])) for (v, p) in zip(votes_info, parties_info)),
		pie.Series((v, dict(color=colors[p])) for (v, p) in zip(seats_info, parties_info)),
		])
		

if __name__=='__main__':
	import sys
	print from_csv_file(sys.argv[1])