Drawing Arcs
D3 can generate the arcs required for drawing a pie chart.
We'll cover the following...
We are going to start drawing the arcs of the pie. D3 comes with a function for helping us draw the arcs. First, we need to decide what the radius of the overall pie will be. The radius is the distance from the center of the circle to the edge.
Setting the radius
The pie should take up the entire space of the container. We can calculate the radius by dividing the width of the container by two. In the script, we are going to store the radius at the location where we set the dimensions. We will define a variable called radius
.
// Dimensionslet dimensions = {width: 600,height: 600,margins: 10,};dimensions.ctrWidth = dimensions.width - dimensions.margins * 2dimensions.ctrHeight = dimensions.height - dimensions.margins * 2const radius = dimensions.ctrWidth / 2
D3 will need to know the radius because each arc will be the size of the radius. Arcs are drawn from the center of the circle to the edge.
Arc generator
With the radius and data ready, let’s draw the arcs. At the bottom of the draw()
function, we will replace the console statement with a variable called arc
. Its value will be the d3.arc()
function.
const arc = d3.arc().outerRadius(radius).innerRadius(0)
The arc()
function will return a function that can draw an arc. It is similar to the line()
function we dealt with in the previous project.
What is the difference between the arc and pie functions?
The
pie()
function will format your data, whereas thearc()
function will draw an arc.
The arc()
function will need to know the radius of our pie. We can set the radius by chaining a function called outerRadius()
. We are passing in the radius
variable to the function.
The outer radius will tell D3 to draw the arc from the center of the circle to whatever value we pass into this function. When we draw the arc, we are going to be drawing it directly at the center of the container. The arc will be drawn to the distance of whatever we pass into the outerRadius()
function. Since the radius
variable is equal to half the size of the container, the arcs should take up the entire room of the container when we draw them. You will see what this looks like in a moment.
There is another function we will need to chain. We are chaining the innerRadius()
function with the value 0
passed in.
The innerRadius()
function will add space at the center of the pie. This will turn it into a donut chart. We will talk about donut charts later. For now, passing in 0
will prevent D3 from drawing a donut chart.
Drawing the arcs
Let’s try drawing the arcs. The arc()
function will return a function we can call to start drawing the arcs. We are going to want to call this function on a <path>
element. There will be multiple <path>
elements, so we should create a group for our <path>
elements. At the bottom of the draw()
function, we will add the following: