Figure 15-16: Plotting images

Portfolio Categories: All Graphics and SGR Book Graphics.

Drawing with Images in R Graphics using Transparency

Drawing with Images using Transparency


# A PDF version utilizing transparency -----------------------------------------

kittenPNG = readPNG("illustrations/kitten-BW.png")
skullPNG = readPNG("illustrations/skull.png")

skull = skullPNG
kitten = kittenPNG

skull2 = as.raster(skull)              # Convert skull to raster
kitten2 = as.raster(kitten)            # Convert kitten to raster

# Some Data from Google ngrams showing average occurance of skull/s 
# and kittens/cats averaged by decade.  Decade/skulls/Kittens
d0 = c(1900, 1.60, 1.65)
d1 = c(1910, 1.59, 1.67)
d2 = c(1920, 1.45, 1.86)
d3 = c(1930, 1.46, 1.76)
d4 = c(1940, 1.37, 1.73)
d5 = c(1950, 1.32, 1.68)
d6 = c(1960, 1.26, 1.66)
d7 = c(1970, 1.19, 1.96)
d8 = c(1980, 1.08, 2.26)
d9 = c(1990, 1.06, 2.45)

kdata = rbind(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9)
kdata = data.frame(kdata)
row.names(kdata) = kdata$V1
colnames(kdata) = c("Decade", "Skulls", "Kittens")

                                       # Create a pdf output file
pdf(file = "illustrations/fig-15-16-images-plot-BW.pdf",
  width = 6,                           # Width at 6 inches
  height = 4)                          # Height at 4 inches


plot(x = kdata$Decade,                 # Set up background plot
  y = kdata$Kittens,  
  xlim = c(1890, 2000),                # Set range of x axis     
  ylim = c(0, 4),                      # Set range for y axis
  xlab = "Kittens v. Skulls",          # Create X axis label
  ylab = "Occurence Rate (x10,000)",   # Create Y axis label
  type = "l")                          # Connect points with a line

points(x = kdata$Decade,               # Add points for skulls
  y = kdata$Skulls,
  type = "l",                          # Connect points with a line
  lty = 2)                             # Use dashed line    

rasterImage(image = kitten2,           # Add kitten images 
  xleft = kdata$Decade - 3,            # Left x values
  xright = kdata$Decade + 3,           # Right x values for kittens
  ybottom = kdata$Kittens - .3,        # Bottom y values    
  ytop = kdata$Kittens + .3)           # Top y values for kittens

rasterImage(image = skull2,            # Add skull images 
  xleft = kdata$Decade - 2,            # Left x values    
  xright = kdata$Decade + 2,           # Right x values for kittens
  ybottom = kdata$Skulls - .25,        # Bottom y values    
  ytop = kdata$Skulls + .25)           # Top y values for kittens 

dev.off()                              # Close pdf file and output