Adding Labels
We can use the ‘call()’ function to reuse the same selection multiple times, which is useful when creating multiple labels.
We'll cover the following...
We are going to add some labels to the pie chart. Labels will help the reader understand each slice of the pie. Once we add some labels, a new problem will become apparent. We will talk about that in a moment. Let’s begin adding some labels.
Drawing labels
We will be working under the section where we drew the shapes. We are going to create a group separate from the arcs. We are going to create a copy of the arcs group selection. The variable will be renamed to labelsGroup
.
// Draw Shapesconst arcsGroup = ctr.append('g').attr("transform",`translate(${dimensions.ctrHeight / 2}, ${dimensions.ctrWidth / 2})`)const labelsGroup = ctr.append('g').attr("transform",`translate(${dimensions.ctrHeight / 2}, ${dimensions.ctrWidth / 2})`).classed('labels', true)
The group will be positioned at the center of the pie. D3 comes with a function that will position a label relative to the center of the pie. This is why we are centering the group. Otherwise, the labels may not get positioned correctly.
In addition, we are adding a class called labels
. The labels
class will set the font size and family. You can check the CSS section for the styles that come with this class. They’re not D3 specific.
Let’s start adding some text elements to this group. At the bottom of the function, we will make a selection ...