Adding a legend to a pie chart

Sometimes, we might wish to use a legend to annotate a pie chart instead of using labels. In this recipe, we will learn how to do this using the legend() function.

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=NA, clockwise=TRUE, col=brewer.pal(7,"Set1"), border="white", radius=0.7, ...

Get R: Data Analysis and Visualization now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.