Skip to content

Instantly share code, notes, and snippets.

@danopia
Last active February 2, 2019 01:00
Show Gist options
  • Save danopia/893f7b5395574ad6442825b052e04337 to your computer and use it in GitHub Desktop.
Save danopia/893f7b5395574ad6442825b052e04337 to your computer and use it in GitHub Desktop.
coffeescript pie chart svg renderer
<svg viewBox="-1 -1 2 2" style="transform: rotate(-90deg)">
{{#each pieSlices}}
<path d={{pathData}} fill={{color}}></path>
{{/each}}
</svg>
# adapted from https://hackernoon.com/a-simple-pie-chart-in-svg-dbdd653b6936
getCoordinatesForPercent = (percent) ->
x = Math.cos(2 * Math.PI * percent)
y = Math.sin(2 * Math.PI * percent)
[x, y]
colors = ["#8eb021","#3b7fc4","#d04437","#f6c342","#654982","#f691b2","#999999","#815b3a","#f79232","#59afe1","#f15c75"]
->
cumulativePct = 0
# issues can be doubleCounted so issueCount doesn't work
valueSum = @results.reduce ((a,b) -> a+b.value), 0
for idx, slice of @results
slicePct = slice.value / valueSum
largeArcFlag = if slicePct > .5 then 1 else 0
[startX, startY] = getCoordinatesForPercent(cumulativePct)
cumulativePct += slicePct
[endX, endY] = getCoordinatesForPercent(cumulativePct)
pathData: [
"M #{startX} #{startY}" # Move
"A 1 1 0 #{largeArcFlag} 1 #{endX} #{endY}" # Arc
"L 0 0", # Line
].join(' ')
color: colors[idx % colors.length]
// adapted from https://hackernoon.com/a-simple-pie-chart-in-svg-dbdd653b6936
var colors, getCoordinatesForPercent;
getCoordinatesForPercent = function(percent) {
var x, y;
x = Math.cos(2 * Math.PI * percent);
y = Math.sin(2 * Math.PI * percent);
return [x, y];
};
colors = ["#8eb021", "#3b7fc4", "#d04437", "#f6c342", "#654982", "#f691b2", "#999999", "#815b3a", "#f79232", "#59afe1", "#f15c75"];
(function() {
var cumulativePct, endX, endY, idx, largeArcFlag, ref, results, slice, slicePct, startX, startY, valueSum;
cumulativePct = 0;
// issues can be doubleCounted so issueCount doesn't work
valueSum = this.results.reduce((function(a, b) {
return a + b.value;
}), 0);
ref = this.results;
results = [];
for (idx in ref) {
slice = ref[idx];
slicePct = slice.value / valueSum;
largeArcFlag = slicePct > .5 ? 1 : 0;
[startX, startY] = getCoordinatesForPercent(cumulativePct);
cumulativePct += slicePct;
[endX, endY] = getCoordinatesForPercent(cumulativePct);
results.push({
pathData: [
`M ${startX} ${startY // Move
}`,
`A 1 1 0 ${largeArcFlag} 1 ${endX} ${endY // Arc
}`,
"L 0 0" // Line
].join(' '),
color: colors[idx % colors.length]
});
}
return results;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment