# coding: utf-8
#!/usr/bin/env python
from __future__ import division
import matplotlib.pyplot as plt
from matplotlib.pyplot import annotate
from matplotlib.colors import rgb_to_hsv, hsv_to_rgb, ColorConverter, rgb2hex
from numpy import array, sin, cos, pi
def pie_colors(n, base_color='#1241dd'):
""" Generate suitable colors, adapted from:
http://stackoverflow.com/a/5651670/878419 """
cc = ColorConverter()
r, g, b = cc.to_rgb(base_color)
color = array([[r, g, b]])
hue = rgb_to_hsv(color)[0, 0, 0]
colors = []
step = 1 / n
for i in range(n):
next_color = rgb_to_hsv(color)
next_color[0, 0, 0] = (hue + step*i) % 1.0
rgb_color = hsv_to_rgb(next_color)
r = rgb_color[0, 0, 0]
g = rgb_color[0, 0, 1]
b = rgb_color[0, 0, 2]
colors.append(rgb2hex((r, g, b)))
return colors
fig = plt.figure(figsize=(7, 4))
ax = fig.add_subplot(111)
# Data
fracs = [45, 34, 10, 8, 1, 1, 1]
labels = ("USA", "Deutschland", "Taiwan", "Norwegen", "Japan", "Spanien",
u"Großbritannien")
pieColors = pie_colors(len(fracs))
ax.set_position([0.2, 0.0, 0.4, 0.75])
p = plt.pie(fracs, startangle=90, colors=pieColors)
plt.axis("equal")
# Annotations
y1s = []
for p1, l1, f1 in zip(p[0], labels, fracs):
r = p1.r
dr = r*0.1
t1, t2 = p1.theta1, p1.theta2
theta = (t1+t2)/2.
xc, yc = r/2.*cos(theta/180.*pi), r/2.*sin(theta/180.*pi)
x1, y1 = (r+dr)*cos(theta/180.*pi), (r+dr)*sin(theta/180.*pi)
if x1 > 0 :
x1 = r+2*dr
ha, va = "left", "center"
tt = -180
cstyle = "angle,angleA=0,angleB=%f" % (theta,)
else:
x1 = -(r+2*dr)
ha, va = "right", "center"
tt = 0
cstyle = "angle,angleA=0,angleB=%f" % (theta,)
# Prevent overlapping text
y1 = round(y1*10)/10
if any([(abs(y1 - y) < 0.15) for y in y1s]):
y1 = max(y1s) + 0.15
l1 = l1 + '; ' + str(f1) + '%'
annotate(l1, (xc, yc), xycoords="data", xytext=(x1, y1), textcoords="data",
ha=ha, va=va, arrowprops=dict(arrowstyle="-",
connectionstyle=cstyle, patchB=p1))
y1s.append(y1)
plt.title(u"Länderaufteilung 2010", y = 1.2)
plt.savefig("pv-global-2010.svg", transparent=True, bbox_inches='tight')