Create lightweight SVG pie and donut charts without a library and minimal JS

It took me a while to find the resources, but creating charts with SVGs (scalable vector graphics) is not that difficult.

The first place to start is reading this article which gives you the code to create a donut chart:
https://heyoka.medium.com/scratch-made-svg-donut-pie-charts-in-html5-2c587e935d72

It also has great tips on making the charts accessible for screen readers.

The code from that excellent medium article can also be found in this code pen:

As for pie charts the calculations are a bit different but the principles are the same.
You can find lightweight code for pie charts here:

(note: this pen contains jQuery, but it is only for query selectors, so it is easy to refactor it to vanilla JS)

I am now able to add 2 small helper functions to make all the calculations to draw the SVGs and server side render them with handlebars.

I will create 2 functions to update them on client side, but they should be more than 10 lines.

Try this code out before using heavy libraries.
Let me know of any questions. :slight_smile:

2 Likes

This is very nice. I’ll save this for future reference. Thanks for sharing.

1 Like