Search code examples
svgautomatic-ref-countingdonut-chart

How to draw several arcs in an svg circle according to each arc percentage?


I need to represent something like a donut chart in SVG. I was trying to draw several arcs inside the same circle, each one with the length defined by a percentage that is previously givven. But with no luck...

Here is a pic:

enter image description here

What I need is that every region will be dynamically defined according to a percentage previously established.

Does anyone knows how can this be done?


Solution

  • This is how I've used to resolve a similar situation:

    <svg xmlns="http://www.w3.org/2000/svg" height="20" width="20" viewBox="0 0 20 20">
      <circle r="5" cx="10" cy="10" stroke="red" stroke-width="10" />
      <circle r="5" cx="10" cy="10" stroke="green" stroke-width="10" stroke-dasharray="calc(60 * 31.42 / 100) 31.42" transform="rotate(-90) translate(-20)" />
      <circle r="5" cx="10" cy="10" stroke="yellow" stroke-width="10" stroke-dasharray="calc(40 * 31.42 / 100) 31.42" transform="rotate(-90) translate(-20)" />
      <circle r="5" cx="10" cy="10" stroke-width="10" fill="white" />
    </svg>
    

    To calculate percentages You need to calculate the percentage for the last circle "yellow" and then for the second circle "green" you have to calculate the percentage and sum the yellow circle percentage.

    Example:

    • Yellow -> 20% -> calc(20 * 31.42 / 100) 31.42
    • Green -> 30% -> calc(50 * 31.42 / 100) 31.42 (50 = 20(yellow) + 30(green))