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,
cex=0.8,
main="Percentage Share of Internet Browser usage")

legend("bottomright",legend=pielabels,bty="n",
fill=brewer.pal(7,"Set1"))
How to do it...

How it works...

Once again we ordered the browser dataset, created a vector of labels, and made the pie chart with the pie() function call, just as in the previous recipe. However, we set labels to NA this time as we want to create a legend instead of labeling the slices directly.

We added a legend to the bottom-right corner by calling the legend() function. We passed the pielabels vector as the legend argument and set the fill argument to the same RColorBrewer color palette we used for the pie slices.

There's more...

Depending on the number of slices and the desired size of the chart, we can experiment with placing the legend in different places. In this case, we have a lot of slice labels: otherwise, we can place the legend in one single row on top of the chart by setting x to "top" and horiz to TRUE.

There's more...
There's more...
..................Content has been hidden....................

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