In this video, we'll show you how to use a Pie and Doughnut charts in chart.js
Pie and Doughnut charts are very useful at displaying relational proportions between data
Both are considered very alike. Doughnut are actually Pie chart with middle zone cut off
I've already put a blank canvas and included the chart.js library to the jsFiddle
First, I'm going to use the sample data provided in the chart.js documentation
We'll go over each data element in detail later
Next, we'll get the 2d context from our canvas
Then create Chart object from the 2d context
and call Pie() with the data as first agrument
We've successfully setup the Pie chart! Now we'll go in detail for a better understanding
First of data element is "value" which is pretty straightforward
Next is "color", this will be the default color of that pie slice
Next is "highlight", this will be the color when mouse hover over that slice
And the last one is "label" that will show on mouse hover that slice
Next we'll talk about customizing chart options
I'm going to copy the options listed in the chart.js documentation
We can pass these option as a second parameter when calling the Pie() Default value will be used if nothing is passed
The first option I would like to talk about is "percentageInnerCutout"
This option is the one that separate Pie chart from Doughnut chart by specifying how much the middle portion will be cut off
The Pie chart has this default to 0. Let's see how it looks with 50
So we can switch from Pie to Doughnut easily by this changing this value
Next is "segmentShowStroke". This one let you enable or disable stroke on each pie slice
You can also enable or disable the chart animation by toggling "animateRotate" boolean
Moreover, you can change the animation effect with "animationEasing"
Currently we're using easeOutBounce effect
You can find all the available effects at chart.js documentation
I'm going to try "linear" effect
It's a bit slow, so I'm going to speed it up by reducing the "animationSteps"
I guess this should give you some ideas about customizing the chart option :)
Next I'm going to talk about dynamically adding data to the chart with javascript
Let me add a button and click event handler
We'll use chart.js provided method addData()
I'm going to call addData() when clicking the button
Pass the to-be-added data as an argument (with the same syntax as below)
We can also remove the data with the same way by using method removeData()
You can pass the segment index number you want to remove. The most recent segment added will be removed if no index was specified
That's all about Pie and Doughnut chart! Please like or subscribe to support us :)