Monday, May 28, 2012

Pie Plots in R

R is very efficient, when it comes to plots; pie plots often useful in describing population characteristics. Suppose if we are to plot pie diagram (plot), say for following data

Female        Male
   85             161

the following can be the code:


> x = c(85, 161)
    
The above code could produce a dataframe with two values with a single row. The data frame can be seen by mearly executing;
  
> x
[1]  85 161
Now we can think of ploting a pie. The diagram should also possess the following;
1) headding
2) labels with respective percentages
3) a legends which must denote same colors as in pie diagram
The following code could prepare labels with respective percentages:
   
> percent = x/sum(x)*100
> labels = c("Female", "Male")
> pielabels = paste(labels, percent, "%")
Now we need to think about the main plot with a headding "Gender". The following command could produce the final plot:
> pie(x, labels = pielabels, col=brewer.pal(7, "Set2"), main="Gender", cex = 0.75,cex.main=0.75); legend("bottomright", legend = c("female", "male"), fill=brewer.pal(7,"Set2"), cex=0.75)
The resultant plot can look like this.
 
 

No comments:

Post a Comment