piechart.asy 889 B

1234567891011121314151617181920212223242526272829303132333435
  1. /* Example of use:
  2. access piechart;
  3. unitsize (70);
  4. int[] values = {1, 2, 3, 2};
  5. string[] labels = {"a", "b", "c", "very long"};
  6. add(piechart.pie(values, labels, 1.2, green, labelcolor=blue));
  7. */
  8. picture pie (int[] values, string[] labels={}, real distance = 0.5, pen color = rgb(1,1,1), pen labelcolor = rgb(0, 0, 0)) {
  9. picture opic;
  10. // unitsize(100);
  11. int total = 0;
  12. for (int i: values) {
  13. total += i;
  14. }
  15. if (total != 0) {
  16. real last = 0;
  17. for (int i = 0; i < values.length; ++i) {
  18. real current = last+values[i]*360/total;
  19. filldraw(opic, arc((0,0), 1, last, current) -- (0,0) -- cycle, values[i]/total * color);
  20. if (labels.length == values.length) {
  21. // rotate() 0 angle is upwards. We shift it to match the trigonometric circle.
  22. label (opic, labels[i], rotate((current+last)/2-90) * (0, distance), labelcolor);
  23. }
  24. last = current;
  25. }
  26. }
  27. return opic;
  28. }