Created
December 17, 2014 12:23
-
-
Save evuez/f1371128c360ecec9503 to your computer and use it in GitHub Desktop.
Donut chart generator
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
from math import cos, sin, radians | |
def piechart(data, width=100, height=100, stroke=40): | |
center_x = width / 2 | |
center_y = height / 2 | |
radius = min([center_x, center_y]) - 5 | |
paths = [] | |
sum_ = sum(data.keys()) | |
dx = radius | |
dy = _angle = 0 | |
for value, color in data.iteritems(): | |
angle = _angle + value / (sum_ / 360.0) | |
x = cos(radians(angle)) * radius | |
y = sin(radians(angle)) * radius | |
abs_x, abs_y = center_x + x, center_y + y | |
abs_dx, abs_dy = center_x + dx, center_y + dy | |
paths.append( | |
""" | |
<path | |
d="M{cx},{cy} L{adx},{ady} A{r},{r} 0 {la},1 {ax},{ay}z" | |
fill="{c}" | |
/> | |
""".format( | |
cx=center_x, | |
cy=center_y, | |
adx=abs_dx, | |
ady=abs_dy, | |
r=radius, | |
la=int(value > sum_ / 2.0), | |
ax=abs_x, | |
ay=abs_y, | |
c=color) | |
) | |
dx, dy = x, y | |
_angle = angle | |
paths.append(""" | |
<circle cx="{cx}" cy="{cy}" r="{r}" fill="white" /> | |
""".format(cx=center_x, cy=center_y, r=radius - stroke) | |
) | |
return ''.join(paths) | |
data = { | |
20: 'red', | |
70: 'blue', | |
15: 'orange', | |
38: 'green' | |
} | |
width = height = 400 | |
chart = """ | |
<svg width="{width}px" height="{height}px" xmlns="http://www.w3.org/2000/svg"> | |
{piechart} | |
</svg> | |
""".format(width=width, height=height, piechart=piechart(data, width, height, 40)) | |
with open('chart.svg', 'w') as out: | |
out.write(chart) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment