Book Image

R Graphs Cookbook Second Edition

Book Image

R Graphs Cookbook Second Edition

Overview of this book

Table of Contents (22 chapters)
R Graphs Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

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")

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...