# 15.5 Incorporating images into plots ==================================== 15.5
# Kittens and Skulls -- raster images
library("png") # Load the png library
# Then read kitten & skull images
kittenPNG = readPNG("illustrations/kitten-BW.png")
skullPNG = readPNG("illustrations/skull.png")
skull = skullPNG[,,-4] # remove alpha channel
kitten = kittenPNG[,,-4] # remove alpha channel
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) # Combine into data frame
row.names(kdata) = kdata$V1 # Set years as row names
colnames(kdata) = # Set up column names
c("Decade", "Skulls", "Kittens")
# Create a png output file
png(filename = "illustrations/fig-15-15-images-plot.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(mar = c(4.2, 4, 1, 1)) # Set margin widths in lines
plot(x = kdata$Decade, # Set up background plot
y = kdata$Kittens,
xlim = c(1890, 2000), # Set x range
ylim = c(0, 4), # Set y range
xlab = "Kittens v. Skulls", # Create X axis label
ylab = "Occurence Rate (x10,000)", # Create Y axis label
type = "l") # Use lines without points
points(x = kdata$Decade, # Add skull points
y = kdata$Skulls,
type = "l", # Connect with lines
lty = 2) # Use dashed line
rasterImage(image = kitten2, # Add kitten images
xleft = kdata$Decade - 3,
xright = kdata$Decade + 3, # Left & right x values for kittens
ybottom = kdata$Kittens - .3,
ytop = kdata$Kittens + .3) # Top & bottom y values for kittens
rasterImage(image = skull2, # Add skull images
xleft = kdata$Decade - 2,
xright = kdata$Decade + 2, # Left & right x values for skulls
ybottom = kdata$Skulls - .25,
ytop = kdata$Skulls + .25) # Top & bottom y values for skulls
dev.off() # Ouput png file
Figure 15-15: Drawing with Images
Portfolio Categories: All Graphics and SGR Book Graphics.