75 lines
No EOL
2.3 KiB
Python
75 lines
No EOL
2.3 KiB
Python
from svg.charts import pie
|
|
import math
|
|
from lxml import etree
|
|
|
|
def createPie(data, gaps = 0):
|
|
total = sum(data.values())
|
|
colours = ['#268ED7','#6A4F8D', '#A03D4F','#DC7432','#F6DC3B','#76B33B', '#267B60']
|
|
className = "hoverTitles" if len(data) > 9 else ""
|
|
svg = '<svg viewBox="-115 -115 230 230" xmlns="http://www.w3.org/2000/svg" class="%s">' % className
|
|
numbers = ""
|
|
position = 90
|
|
i = 0
|
|
|
|
for e in sorted(data.keys()):
|
|
data[e] = data[e] / total
|
|
|
|
arc = data[e] * 360.;
|
|
diff = polarToCartesian(0,0,5, position+0.5*arc) if gaps > 0 else {'x':0, 'y': 0}
|
|
d = describeArc(float(diff['x']), float(diff['y']), 60, position, position+arc)
|
|
# print(position, arc)
|
|
svg += '<path fill="none" stroke="%s" stroke-width="60" d="%s" />' % (colours[i%len(colours)], d)
|
|
# tRadius = 105 if i%2 else 95
|
|
t = polarToCartesian(0,0, 100, position+0.5*arc)
|
|
svg += '<text x="%s" y="%s" font-family="sans-serif" font-size="12" style=" stroke:color: black;" text-anchor="middle" transform="rotate(%s %s,%s)">%s</text>' % (t['x'], t['y'], position+0.5*arc, t['x'],t['y'], e)
|
|
position += arc
|
|
i+=1
|
|
|
|
svg += numbers
|
|
svg += "</svg>"
|
|
return svg
|
|
# data is now in fractions
|
|
|
|
def polarToCartesian(centerX, centerY, radius, angleInDegrees):
|
|
"""
|
|
Adapted from http://stackoverflow.com/a/18473154
|
|
"""
|
|
angleInRadians = (angleInDegrees - 90) * math.pi / 180.0;
|
|
|
|
return {
|
|
"x": str(centerX + (radius * math.cos(angleInRadians))),
|
|
"y": str(centerY + (radius * math.sin(angleInRadians)))
|
|
}
|
|
|
|
def describeArc(x, y, radius, startAngle, endAngle):
|
|
"""
|
|
Adapted from http://stackoverflow.com/a/18473154
|
|
"""
|
|
start = polarToCartesian(x, y, radius, endAngle)
|
|
end = polarToCartesian(x, y, radius, startAngle)
|
|
|
|
largeArcFlag = "0" if endAngle - startAngle <= 180 else "1";
|
|
|
|
d = " ".join([
|
|
"M", start['x'], start['y'],
|
|
"A", str(radius), str(radius), "0", largeArcFlag, "0", end['x'], end['y']
|
|
]);
|
|
|
|
return d
|
|
|
|
|
|
# g = pie.Pie({})
|
|
# options = dict(
|
|
# width=640,
|
|
# height=480,
|
|
# fields=list(data.keys()),
|
|
# graph_title='Question 7',
|
|
# # expand_greatest = True,
|
|
# show_data_labels = True,
|
|
# compress=False,
|
|
# css_inline=True,
|
|
# )
|
|
# g.__dict__.update(options)
|
|
# g.add_data({'data': list(data.values()), 'title': 'Female'})
|
|
# # g.add_data({'data': [0, 2, 1, 5, 4], 'title': 'Male'})
|
|
# return str(g.burn()) |