Introduction
Know your problem
Know your data
Visualize your data - pie charts
Work with your chart
16. Add value labels
Check yourself

Instruction

If exact values are important to your story, add value labels to the chart.

If there are just a few numbers on our chart and we want to show their exact values, we can show the numbers in text labels. These labels are placed on or near the wedge representing them in the pie.

Don't use too many decimal places in the labels. It will add clutter to the chart without adding any relevant information. Limit yourself to two decimal places. That's precise enough, and your chart will look better.

In R, you can round numbers by calling the round function. It looks like this:

round(x, digits = 0)

Round takes two arguments: x (the numbers that we want to round) and digits (how many decimal places we want). The digits argument is optional; if you don't specify it, numbers will be rounded to the nearest whole number (zero decimal places) by default.

To add text labels to our pie chart, we will use geom_text() with some appropriate arguments:

+ geom_text(aes(x = 1.7, label = value_labels), position = position_stack(vjust = 0.5))

The three arguments are: x (the distance between wedge and label), label (text describing the labels, which will appear next to each wedge), and position (where the label will be placed). In this case, labels will appear near each wedge, at the center of the wedge angle.

We will also want to add a percent sign to the labels. We'll use the paste0(text1, text2) function to do this. It adds text2 to text1. Here it is for one of our values:

paste0(24, "%") = "24%"

Exercise

Add value labels to the pie object. Use the above geom_text() command and set the label as paste0(round(percent), "%"). Save this result to pie object.

When you're done, press the Run and Check Code button to check your code.

Stuck? Here's a hint!

You should write:

geom_text(aes(x = 1.7, label = paste0(round(percent), "%")), position = position_stack(vjust = 0.5))