Labeling a pie chart with percentage values for each slice

In this recipe, we will learn how to add the percentage values in addition to the names of slices, thus making them more readable.

Getting ready

Once again in this recipe, we will use the browsers.txt example dataset, which contains data about the usage percentage share of different Internet browsers.

How to do it...

First, we will load the browsers.txt dataset and then use the pie() function to draw a pie chart:

browsers<-read.table("browsers.txt",header=TRUE)
browsers<-browsers[order(browsers[,2]),]

pielabels <- sprintf("%s = %3.1f%s", browsers[,1],
100*browsers[,2]/sum(browsers[,2]), "%")

pie(browsers[,2],
labels=pielabels,
clockwise=TRUE,
radius=1,
col=brewer.pal(7,"Set1"),
border="white",
cex=0.8,
main="Percentage Share of Internet Browser usage")
Getting ready

How it works...

In the example, instead of using just the browser names as labels, we first created a vector of labels that concatenated the browser names and percentage share values. We used the sprintf() function that returns a character vector that contains a formatted combination of text and variable values. The first argument to sprintf() is the full character string in double quotes, where the % notation is used to fill in values dynamically and thus create a vector of strings for each slice. %s refers to a character string (browsers[,1] which is the second argument). %3.1 refers to a three-digit value with one significant decimal place (the percentage share value calculated as the third argument). The second %s refers to the character "%" itself, which is the last argument.

We make the pie chart using the same pie() function call as in the last recipe, except that we set labels to the newly constructed vector, pielabels.

There's more...

We can adjust the size of the chart and the text labels by using the radius and cex arguments, respectively.

See also

In the next recipe, we will see how to add a legend to a pie chart.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.254.245