Figure 12-15: A Pie Chart

Portfolio Categories: All Graphics and SGR Book Graphics.

Demonstration of R Graphics Pie Chart

An R Graphics Pie Chart of Corruption Scores


# Read in data
myData = read.delim(file = "http://www.kktg.net/R/Chapter12Data.txt",
  colClasses = c("character", "numeric", "numeric", "numeric"), header = T)

# Create categorical versions of the dem/polity data
myData$dem = 
  ifelse(myData$P4 > 7, 1, 0)          # Dem if Polity >7    
myData$corrupt = 
  ifelse(myData$CPI < 4, 1, 0)         # Corrupt if CPI<4
myData$cGDPk = myData$cGDP/1000        # Per capita GDP in 1000s

# Remove all observations with missing data
myData = myData[!is.na(myData$CPI) & !is.na(myData$P4),]

# 12.7 Pie charts ========================================================= 12.7

CPIbreaks = cut(myData$CPI,            # Create factor dividing CPI data
  c(0, 3.3, 6.6, 10))                  #  into 3 bins    

CPIcounts = tapply(myData$CPI,         # Create vector of bar heights
  CPIbreaks,                           #  based on the bins we created       
  length)                              #  counting num of obs in each bin

names(CPIcounts) = paste(              # Create labels by pasting
  c("High",                            #   low/medium/high text     
    "Medium",
    "Low"),
  names(CPIcounts),                    #   to existing bin labels
  sep = "--")                          #   separated by "--"

png(filename = "illustrations/fig-12-15-piechart-BW.png",
  units = "in",                        # Set measurements in inches
  res = 1200,                          # Set resolution at 1200dpi
  width = 6,                           # Width at 6 inches
  height = 4))                         # Height at 4 inches

par(mai = c(.25, .25, .75, .25))       # Change margins for pie chart

pie(CPIcounts,                         # Create a pie chart w/CPI shares
  col = c("white", "gray", "darkgray"),# Set colors
  main = "Corruption")                 # Add a title

dev.off()                              # Output png file