How to create a pie chart using Javascript and HTML

In this blog post I am going to walk you through the process of creating a pie chart using javascript and html. The only external library I am using is jQuery. First let’s see a demo:

See the Pen pie chart by Grepsoft (@grepsoft) on CodePen.default

Enter data points and then hit Enter data. You will see input fields for your points. Just enter those and then hit the Generate Pie button. You should see a nice pie chart.

To generate the pie I am using HTML canvas. The canvas API can be used to do some very cool things like animations, graphics, photo and video processing. I am using the arc function to draw the pie chart. The signature of an arc function looks like this:

arc(x, y, radius, startAngle, endAngle, anticlockwise)

x and y is the arc’s center. Radius is obvious. Startangle is where the arc should start and endAngle is where it ends. One thing to keep in mind is that the angles are measured in radians. You need to convert degrees to radians and this can be done using this formulat:

radian = (PI / 180) * degrees;

If you draw an arc with the above method it will not be properly drawn as in not a properly drawn pie chart. Which is why I am drawing a line from the arc edge to the center right after I draw an arc like this:

    ctx.arc(x,y,radius, startAngle, endAngle, true);
    ctx.lineTo(x,y);

Now a little on converting data points to angles. I add all the data points then find percent by:

percent = data_point / Total

after getting the percent we simply multiply by 360 to get the angle:

angle = percent * 360

Say you have two data points each with value of 2. Then total is 4 and percent will be 2/4 = 50% and then 50% of 360 = 180. This will be two Pie’s. You can verify using the demo above.

As a challenge see if you can find a way to write the percent value on the corresponding pie either on mouse hover or all the time.

Leave a Reply

Your email address will not be published. Required fields are marked *