DEV Community

Cover image for How to create an interactive donut chart using SVG

How to create an interactive donut chart using SVG

Mustapha Aouas on December 10, 2021

In this post, we'll make an SVG donut chart with clickable slices/parts. I'll start by explaining the issue with the most common way to implement a...
Collapse
 
hdaghash profile image
Hasan Daghash

That's really an interesting article, thank you Mustapha for the great explanation
One drawback I noticed is that in the case of only one segment and it is set to 100% then the path will disappear if it's 99.999 it will work!!

Collapse
 
mustapha profile image
Mustapha Aouas

Hey Hassan thank you for your feedback.
Good catch indeed! (i’ll edit the post, to mention this :)

Collapse
 
samscholefield profile image
Sam Scholefield

Hey Hasan, I just noticed the same thing. The solution below only adjusts the drawing logic, and not the underlying data (so your slices are still accurate). Its ugly, unfortunately I couldn't solve it any more elegantly, but it works for me:

 /**
   * converts percentage to angle
   * @param percent
   * @returns angle as degrees as number
  */
  private percentToDegrees(percent: number): number {
    return percent * 3.6 === 360 ? 359.99 : percent * 3.6
  }

Enter fullscreen mode Exit fullscreen mode
Collapse
 
crashlaker profile image
Carlos Aguni • 顾宁

awesome!!

Collapse
 
saswat3115 profile image
Saswat Mohanty

nicely explained all the attributes of an svg arc

Collapse
 
knownasilya profile image
Ilya Radchenko

Any ideas why my second slice has a droop in the inner arc? I tried all variations of flags :D

<path fill="green" d="
                M 87.15724127386972 16.543469682057086
                A 50 50 0 0 0 3.015368960704585 32.898992833716555
                L 31.206147584281833 43.15959713348662
                A 30 30 0 0 1 64.86289650954788 36.61738787282283
            ">
            <title>slice</title>
        </path>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mustapha profile image
Mustapha Aouas

Hello there,

I can only guess that the radius of the inner cercle is wrong, it should be 20 instead of 30 (the flags are good ^^) 👇

<path fill="green" d="
                M 87.15724127386972 16.543469682057086
                A 50 50 0 0 0 3.015368960704585 32.898992833716555
                L 31.206147584281833 43.15959713348662
                A 20 20 0 0 1 64.86289650954788 36.61738787282283
            ">
            <title>slice</title>
</path>
Enter fullscreen mode Exit fullscreen mode
Collapse
 
knownasilya profile image
Ilya Radchenko

Yes, that was it! How do you understand the radius x/y? Having a hard time with that part conceptually.

Collapse
 
knownasilya profile image
Ilya Radchenko

Image description

Collapse
 
suhakim profile image
sadiul hakim

That is great!❤

Collapse
 
mustapha profile image
Mustapha Aouas

Thank you 🙏🙏