Search⌘ K

Fixing the Pie Chart

Explore how to improve pie charts in D3.js by adjusting label positions, filtering out unreadable labels, and maintaining the correct slice order. Understand the use of filter and sort functions along with creating donut charts to enhance readability and presentation in your data visualizations.

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.

Javascript (babel-node)
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 ...