Fixing the Pie Chart
We'll use a second arc for displaying labels to keep things from getting clustered in a pie chart.
We'll cover the following...
Let’s talk about the issues with our pie chart. The first issue is with how the labels are drawn. The age group should appear above the population. At the moment, the age group and population are side-by-side. They do not have much room to breathe.
Positioning the labels
We are going to modify the coordinates of the labels to position the age group above the population.
labelsGroup.selectAll("text").data(slices).join("text").attr("transform", d => `translate(${arc.centroid(d)})`).call(text => text.append("tspan").attr("y", -4).attr("font-weight", "bold").text(d => d.data.name)).call(text => text.append("tspan").attr("x", 0).attr("y", 9).text(d => d.data.value))
For the first selection, we are modifying the y
attribute. The value for this attribute is -4
. This value will move the attribute higher.
For the second tspan
selection. we are modifying the x
and y
attributes. The y
attribute is being set to 9
. We are resetting the x
attribute to 0. The reason we are resetting the x coordinate is that the text will not be positioned directly under the age group. It will be moved over to the left. The x coordinate will need to be reset to 0 so that the age group and population are aligned.
Let’s view the output.
The labels are more readable. However, the smaller slices are difficult to read. This is a common problem for some visualizations. You may have shapes that are too small to have ...