Figure 12-17: A Mosaic Plot

Portfolio Categories: All Graphics and SGR Book Graphics.

Demonstration of R Graphics Mosaic Plot

A More Complex Mosaic Plot of Corruption by Polity

 
# 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),]


# A little more complex 10x4 table

myTable2 = table(                      # Create a contingency table
  cut(myData$P4,                       #   with x = polity score
    quantile(myData$P4)),              #   cut into quantiles (i.e. same num     
                                       #   of observations in each group)
  round(myData$CPI, 0))                #   and y = rounded CPI score.

myTable2                               # Display contingency table

png(filename = "illustrations/fig-12-17-mosaicplot2.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(.5, .5, .3, .25))          # Change margins for png graphs

mosaicplot(myTable2,                   # Create mosaic plot for myTable2
  main = NA,                           # Turn off default plot title
  xlab = "PolityIV",                   # Set x axis label
  ylab = "CPI 0=most corrupt")         # Set y axis label

dev.off()                              # Output png file