Draw a Pie Chart
Learn how to draw a pie chart using an angle generator.
We'll cover the following
Introduction
After exploring the steps needed to draw a pie chart in the previous two lessons, it is time to dive into creating a pie chart. A pie chart is used to show the proportion of different quantities. We will draw a pie chart in D3.js with the help of the following two APIs.
d3.arc()
d3.pie()
Example
Let’s demonstrate the pie chart by taking some dummy data that shows programming languages used by developers in 2020.
Explanation
As shown in the above code in:
- Line 29-33: First, we have defined
p_chart
. We have selectedpie
, which doesn’t exist, so it will return an empty selection. Now we are joiningdata()
with our return selection throughdata(pie(data))
. Then we have appended theg
tag for each data point. - Line 34-38 is where the pie chart is drawn with the help of an
arc
. With the help ofordinalScale()
, we have assigned a color to each arc. - Line 39-42: We have added the name of the language to the respective arc by using the
text()
method. Thistext()
will be placed at the centroid of each arc with the help of thearc.centroid()
method.