Ian McFarlan

Simple SVG Pie Charts

19 Apr 2017

You’ve got a percentage value and you need a simple pie chart output; SVGs and a bit of JavaScript to the rescue. SVG support is pretty widespread these days and is only going to get better.

Disclaimer: I am have a fine arts background and math isn’t my forté. That said this technique has served me well for simple, dynamic pie charts. 

Below are snippets of CSS, HTML, and JavaScript. I’ve opted for vanilla CSS and JavaScript for portability and versatility. Feel free to SASS it up. Maybe stay away from jquery for this though; no need for it with something this simple.

This example would render a pie chart with a diameter of 80 pixels. This technique only works well when working with a single percentage value. For more roubust pie charts have a look at the further reading section below.

CSS

.pie-chart {
    display: block;
    max-width: 80px;
    max-height: 80px;
    width: 100%;
    float: right;
    margin-top: -10px;
    transform-origin: 50% 50%;
    -moz-transform-origin: 40px 40px;
    -ms-transform: rotate(-90deg);
    transform: rotate(-90deg);
}

.pie-chart[data-percentage="0"],
.pie-chart[data-percentage="1"],
.pie-chart[data-percentage="100"], {
    display: none;
}

.pie-chart svg {
    max-height: 80px;
    border-radius: 50%;
    border: 2px solid #ffffff;
    background: #ffffff;

.pie-chart svg path {
    stroke: #0074a2;
    stroke-width: 1px;
    fill: #0074a2;
    -moz-transform: translate3d(0, 0, -1px);
}

HTML / Emmet

div.pie-chart[data-percentage="35"]

JavaScript

function draw_pie_chart() {
    var percentage, // percentage for the data attribute
        path, // path for svg
        angle, // 1% = 3.6deg; used for coord mapping
        radius = 100, // radius of the pie chart in pixels
        coords = []; // holds Cartesian plane coords for svg path

    percentage = parseInt( document.querySelectorAll( '.pie-chart[data-percentage]' ).getAttribute( 'data-percentage' ) );
    angle = percentage * 3.6;

    coords[0] = radius * Math.cos( Math.PI * angle / 180 );
    coords[1] = radius * Math.sin( Math.PI * angle / 180 );

    path = 'M0,0 L' + radius + ',0 A' + radius + ',' + radius + ' 0 1,1 ' + coords[0] + ',' + coords[1] + ' Z';

    document.querySelectorAll( '.pie-chart svg path' ).setAttribute( 'data-d', path );

} );

Further Reading

My name is Ian McFarlan and I have been a web developer since 2003. I’ve mainly worked in client services and advertising but lately I have been getting my hands dirty with product development.

Work | About | Contact

More Articles