SGR Code from Chapters 14-15

R Code for Chapter 14: Graphics III — The Fun Stuff — Text

# ==============================================================================  
# Chapter 14 -- Graphics III: The fun stuff -- Text
# ==============================================================================

default.par = par()                    # Set default parameters for recovery

# 14.1 Adding text ======================================================== 14.1
                     
myV1 = c(1, 2, 3, 4, 5)                # Set up some temporary data
myV2 = c(5, 7, 3, 9, 8)                       

png(filename = "illustrations/fig-14-1-Text-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

plot(myV1, myV2,                       # Plot the data
  ylim = c(0, 10),                     # Set range for y axis
  type = "b",                          # Set line type connecting dots  
  main = "A bold title on top",        # Add a title at the top
  font.main = 2,                       # Bold for  main title
  cex.main = 2,                        # Set font size for the main title 
  sub = "Subtitle at the bottom",      # Put a subtitle on the bottom
  cex.sub = .75,                       # Set font size for the subtitle
  col.sub = "darkgray",                # Set color for subtitle
  xlab = "This is the x axis",         # Add text for the x axis
  ylab = "This is the y axis",         # Add text for the y axis 
  font.lab = 3,                        # Set axis label font to italic
  col.lab = "black")                   # Set color for axis labels

# A legend 
legend("bottomright",                  # Location of legend
  inset = .025,                        # Distance from edge of plot region
  legend = c("my x1 variable",         # Legend Text
    "my x2 variable"),
  col = c("black", "darkgray"),        # Legend Element Colors
  pch = c(1, 22),                      # Legend Element Styles
  title = "A Legend")                  # Legend title

# Some ad hoc text
text(x = 2.5, y = 5,                   # Add some ad hoc text at x = 2 y = 5
  labels = "Some ad hoc text",         # The text to add
  srt = 45,                            # Rotate 90 degrees
  family = "mono",                     # Use mono-spaced font
  col = "darkgray")                    # Set color to dark green

# Ad hoc text in margin
par(usr = c(0, 1, 0, 1))               # Set usr parameters to 0,1 space
text(x = 1.05, y = .5,                 # Place text just outside right border
  labels = "Ad hoc text in margin",    # Text to use
  xpd = TRUE,                          # Allow text outside of border
  font = 3,                            # Italic font
  cex = 1.25,                          # Font size to 1.25
  srt = 270,                           # Rotate string 270 degrees
  col = gray(.75))                     # Set color to gray .75
     
dev.off()                              # Output png file


# 14.2 Setting up fonts =================================================== 14.2

# 14.2a The built-in fonts =============================================== 14.2a
png(filename = "illustrations/fig-14-2-fonts.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(mfcol = c(2, 2))                   # Set 2x2 grid of plots
plot(myV1, myV2, type = "b",           # A simple plot
  main = "Family = 'sans'",            # A title 
  sub = "The default sans-serif font", # A subtitle
  family = "sans")                     # Set font family to sans

plot(myV1, myV2, type = "o",           # A simple plot
  main = "Family = 'serif'",           # A title 
  sub = "The serif font",              # A sub-title
  family = "serif")                    # Set font family to serif

plot(myV1, myV2, type = "l",           # A simple plot
  main = "Family = 'mono'",            # A title 
  sub = "The mono-spaced font",        # A sub-title
  family = "mono")                     # Set font family to mono

plot(myV1, myV2, type = "p",           # A simple plot
  main = "Variation in font styles",   # A title 
  sub = "Same font family, different styles and sizes",
  family = "serif",                    # Set font family to serif
  font.main = 4, cex.main = 1.75,      # Title in larger bold italic
  font.axis = 2, cex.axis = .75,       # Axis fonts small but bold
  font.sub = 3, cex.sub = .6,          # Subtitle fonts in italic & larger
  font.lab = 1, cex.lab = 1)           # Axis labels plain & default size
     
dev.off()                              # Output png file

# Check windows font mappings
windowsFonts()                         # Show windows font mappings

# 14.2b Remapping windows fonts ========================================== 14.2b

png(filename = "illustrations/fig-14-3-windowsFonts.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(mfcol = c(2, 1))                   # Set up 2 plots vertically
par(mai = c(.85, .85, .5, .25))        # Set margins
windowsFonts(                          # Reassign the sans font 
  sans = "TT Comic Sans MS")           #   to Comic Sans
plot(myV1, myV2, type = "b",           # A simple plot 
  main = "Some Comic Sans Action!",    # A Title
  family = "sans")                     # Font family for plot

windowsFonts(                          # Reassign serif font
  serif = "TT Blackadder ITC")         #   to Blackadder ITC
plot(myV1, myV2, type = "b",           # A simple plot 
  main = 
    "Please don't use this font!",     # A title for the plot
  family = "serif")                    # Font family for plot

dev.off()                              # Output png file

# Reset fonts to defaults (Please!)
windowsFonts(sans = "TT Arial")        # Reset fonts back to defaults
windowsFonts(serif = "TT Times New Roman")  

# 14.2c The Rdevga method for Windows ==================================== 14.2c

# Note that this method requires editing your Rdevga file so that lines
# 15 - 18 (not include blank and comment lines read: 
# TT Century Gothic : plain
# TT Century Gothic : bold
# TT Century Gothic : italic
# TT Century Gothic : bold&italic
# (but without the hashtag at the beginning).

png(filename = "illustrations/fig-14-4-Rdevga method.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(mfcol = c(1, 1))                   # Reset mfcol for just one plot
plot(myV1, myV2, type = "b",           # A simple plot 
  main = "The Rdevga method",          # A Title
  font.main = 15,                      # This should be Century Gothic bold
  font.lab = 12,                       # This should be Courier italic
  font.axis = 7)                       # This should be Times bold

dev.off()                              # Output png file

# 14.3 Titles and Subtitles =============================================== 14.3

# Short example of using text variables for title
myTitle = "My Nice Title"              # Create a txt variable with title
plot(myX, myY, main = myTitle)         # Plot using txt variable title

                     
png(filename = "illustrations/fig-14-5-Title and subtitle-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

plot(myV1, myV2, type = "l",           # A simple plot
  main = "Here is the title",          # The main title
  family = "serif",                    # Use serif family font
  font.main = 2,                       # Set title font to bold
  cex.main = 3,                        # Set title font size to double
  col.main = "darkgray",               # Set title to dark gray
  xlab = NA, ylab = NA)                # Supress axis labels 

title(                                 # Put subtitle on plot
  sub = "This is the subtitle",        # A subtitle
  adj = 1,                             # Put it on right side
  family = "mono",                     # Use mono-spaced font
  font.sub = 2,                        # Use bold for subtitle
  cex.sub = 1.5,                       # Subtitle font size = 1.5
  col.sub = "black")                   # Subtitle color 

title(                                 # Put X axis label on plot
  xlab = "This is the x-axis label",   # X axis label text
  family = "sans",                     # Use sans-serif font
  font.lab = 3,                        # Use italic for x axis label
  cex.lab = 1.25,                      # X-axis label font size 
  col.lab = "darkgray")                # X-axis label color

title(                                 # Put Y axis label on plot
  ylab = "Y is here",                  # Y axis label text
  family = "serif",                    # Use serif font
  font.lab = 2,                        # Use bold for y axis label
  cex.lab = 1.25,                      # Y-axis font size = 1.25
  col.lab = "darkgray",                # Y-axis label color
  las = 2)     

dev.off()                              # Output png file

# 14.4 Legends ============================================================ 14.4

# Set up some data
year = 1990:1996                       # Create a series of years
myV1 = c(10, 11, 12, 9, 14, 10, 11)    # Create some values for myV1
myV2 = c(8, 14, 9, 12, 10, 13, 12)     # Create some values for myV2

png(filename = "illustrations/fig-14-6-legends-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(1, .5, .25, .25))          # Set space around plot

# Create a simple plot
plot(year, myV1,                       # Plot myV1 against year
  ylim = c(0, 20),                     # Set y axis scale
  ylab = NA,                           # Turn off y axis label
  type = "o",                          # Set as line plot with points
  lty = 1,                             # Solid line
  pch = 16)                            # Point style
points(year, myV2,                     # Add myV2 to plot
  type = "o",                          # Set type as line with points
  col = "darkgray",                    # Set color to red
  lty = 2,                             # Dashed line
  pch = 22)                            # Use square box for point style

# Legend 1
legend("topleft",                      # Location of legend
  inset = .025,                        # Distance from edge of plot region
  legend = c("Variable myV1",          # Legend Text
    "Variable myV2"),
  col = c("black", "darkgray"),        # Legend Element Colors
  pch = c(16, 22),                     # Legend Element Styles
  title = "Legend 1")                  # Legend title

# Legend 2
legend(x = 1992.25, y = 20,            # Location of legend on x & y scale
  legend = c("Variable myV1",          # Legend Text
    "Variable myV2"),
  cex = .8,                            # Text size set to .8
  fill = c("black", "darkgray"),       # Legend Element Colors
  title = "Legend 2",                  # Legend Title
  horiz = T,                           # Set legend horizontally
  bg = "light gray")                   # Set color for legend background

# Set up percentage coordinates system for legend
my.usr = par("usr")                    # Save current coordinate units
par(usr = c(0, 1, 0, 1))               # Set coordinate space to 0,1 scales

# Legend 3 Bold Title
par(font = 2, family = "serif")        # Set bold serif font
legend(x = .05, y = .3,                # Location of legend in percent units
  yjust = 1,                           # Put legend below y value
  legend = c("Variable myV1",          # Legend Text
    "Variable myV2"),
  lty = c(1, 2),                       # line types for legend elements
  col = c("black","darkgray"),         # Legend Element Colors
  title = "Legend 3",                  # Legend title
  title.col = gray(.2),                # Legend title color
  text.col = "white",                  # Set text color to be invisible
  bty = "n")                           # No box around legend

par(font = 1, family = "sans")         # Return default font to normal sans

# Legend 3
legend(x = .05, y = .3,                # Location of legend in percent units
  yjust = 1,                           # Put legend below y value
  legend = c("Variable myV1",          # Legend Text
    "Variable myV2"),
  lty = c(1, 2),                       # line types for legend elements
  col = c("black", "darkgray"),        # Legend Element Colors
  title = NA,                          # Legend title turned off
  bty = "n")                           # No box around legend

# Legend 4
legend(x = .95, y = .05,               # Location of legend in percent units
  xjust = 1,                           # Left justify legend box on x coord.
  yjust = 0,                           # Bottom justify legend box on y coord.
  legend = c("Variable myV1",          # Legend Text
    "Variable myV2"),
  lty = c(1, 2),                       # Line type for legend elements
  col = c("black", "darkgray"),        # Legend Element Colors
  pch = c(16, 22),                     # Symbol styles for legend elements
  merge = TRUE,                        # Merge line & symbol for legend elements
  title = "Legend 4",                  # Legend Title
  title.col = gray(.4),                # Legend title color
  box.lty = 9,                         # Legend box line type
  box.lwd = 2,                         # Legend box line width
  box.col = "darkgray")                # Legend box color

dev.off()                              # Output png file

# Putting a legend outside the plot area ---------------------------------------

year = 1990:1996                       # Create a series of years
myV1 = c(10, 11, 12, 9, 14, 10, 11)    # Create some values for myV1
myV2 = c(8, 14, 9, 12, 10, 13, 12)     # Create some values for myV2

# Create a simple plot

png(filename = "illustrations/fig-14-7-legends-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(1.5,  .5, .25, 2))         # Right margin space for legend

plot(year, myV1,                       # Plot myV1 against year
  ylim = c(0, 20),                     # Set y axis scale
  ylab = NA,                           # Turn off y axis label
  type = "o",                          # Set as line plot with points
  lty = 1,                             # Solid line
  pch = 16)                            # Point style

points(year, myV2,                     # Add myV2 to plot
  type = "o",                          # Set type as line with points
  col = gray(.2),                      # Set color
  lty = 2,                             # Dashed line
  pch = 22)                            # Use square box for point style

# Legend outside the plot on right

legend(x = 1996.5, y = 15,             # Location of legend 
  xpd = TRUE,                          # Allow drawing outside plot area
  xjust = 0,                           # Left justify legend box on x
  yjust = .5,                          # Center legend box on y
  legend = c("Variable myV1",          # Legend Text
    "Variable myV2"),
  col = c("black", gray(.2)),          # Legend Element Colors
  pch = c(16,22),                      # Legend Element Styles
  title = "Legend 5",                  # Legend Title
  title.col = gray(.2),                # Legend title color
  box.lty = 1,                         # Legend box line type
  box.lwd = 2)                         # Legend box line width

# Legend outside the plot on bottom
legend(x = 1993, y = -6.5,             # Location of legend
  xpd = TRUE,                          # Allow drawing outside plot area
  xjust = .5,                          # Center legend box on x
  yjust = 1,                           # Top justify legend box on y
  horiz = TRUE,                        # Set legend horizontally
  legend = c("Variable myV1",          # Legend Text
    "Variable myV2"),
  lty = c(1, 2),                       # Line type for legend elements
  col = c("black", gray(.2)),          # Legend Element Colors
  pch = c(16, 22),                     # Symbol styles for legend elements
  merge = TRUE,                        # Merge line & symbol for legend 
  title = "Legend 6",                  # Legend Title
  title.col = gray(.4),                # Legend title color
  box.lty = 1,                         # Legend box line type
  box.lwd = 2,                         # Legend box line width
  box.col = gray(.4))                  # Legend box color

dev.off()                              # Output png file

# 14.5 Simple axes and axis labels ======================================== 14.5

# 14.6 Building more complex axes ========================================= 14.6

# Turning axes off selectively (not in book).
default.par = par()                    # Save parameter settings

myV1 = c(1, 3, 4, 7, 9)                # Set up some x values
myV2 = c(4, 6, 5, 3, 7)                # Set up some y values

par(mfrow = c(2, 2))                   # Create a 2x2 grid of plots     

plot(myV1, myV2, type = "b",           # Plot myV1 with myV2
  main = "xaxt = 'n'",                 # Add main title
  xaxt = "n")                          # Turn off x axis

plot(myV1, myV2, type = "b",           # Plot myVq with myV2
  main = "yaxt = 'n'",                 # Add main title
  yaxt = "n")                          # Turn off y axis

plot(myV1, myV2, type = "b",           # Plot myVq with myV2
  main = "xaxt='n' & yaxt='n'",        # Add main title
  xaxt = "n", yaxt = "n")              # Turn off x & y axes

plot(myV1, myV2, type = "b",           # Plot myVq with myV2
  main = "axes=FALSE",                 # Add main title
  axes = FALSE)                        # Turn off both axes

# Axis Modifications I ---------------------------------------------------------

myV1 = c(1, 3, 4, 7, 9)                # Set up some x values
myV2 = c(4, 6, 5, 3, 7)                # Set up some y values

png(filename = "illustrations/fig-14-8-axes-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

plot(myV1, myV2,                       # Plot myV1 and myV2
  xaxt = "n", yaxt = "n",              # Supress axes
  xlim = c(0, 10))                     # Set x range

axis(side = 1,                         # X axis
  at = c(seq(0, 10, by = 2)))          # tick marks every 2

axis(side = 1,                         # X axis minor tick marks
  at = c(seq(1, 9, by = 2)),           # Set on odd numbers
  labels = NA,                         # No labels for minor tick marks
  tcl = -.25)                          # Shorten minor tick marks

axis(side = 3,                         # Put another axis on top
  at = c(0:10),                        # Ticks at 0-10
  labels = LETTERS[1:11])              # Use alphabet labels

axis(side = 2,                         # Add Y axis
  at = c(3:7),                         # Tick marks from 3-7 by 1
  las = 1,                             # Rotate labels perpendicular to axis
  lwd = 0,                             # Turn off axis line
  lwd.ticks = 2,                       # Set tick width to 2
  col.ticks = gray(.3))                # Set tick color

dev.off()                              # Ouput png file

# Axis positions and modifications II ------------------------------------------

png(filename = "illustrations/fig-14-9-more axes.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(1, 1, .5, .25))

plot(myV1, myV2,                       # Plot myV1 and myV2
  xaxt = "n", yaxt = "n",              # Suppress axes
  xlim = c(0, 10),                     # Set x range
  xlab = NA)                           # Turn off X label  

axis(side = 1,                         # Set up new X axis
  at = c(seq(0, 10, by = 2)),          # Tick marks trom 0-10 by 2
  labels = c("Zero", "Two", "Four",    # Labels for tick marks
    "Six", "Eight", "Ten"),
  family = "serif",                    # Set font
  cex.axis = 1.5,                      # Increase font size by 50%
  las = 2,                             # Make labels perpendicular to axis
  line = 1)                            # Put axis 1 line into the margin

axis(side = 2,                         # Set up new Y axis
  at = c(3:7),                         # Set tick marks from 3-7 by 1
  font = 4,                            # Set font to bold italic
  lwd.ticks = 2,                       # Set major tick line width at 2
  pos = -.5)                           # Set axis at -.5 on X scale

axis(side = 2,                         # Overlay minor tick marks on Y axis
  at = c(3.5:6.5),                     # Put them on the .5 marks
  labels = NA,                         # No labels
  tcl = -.25,                          # Set length of tick marks
  pos = -.5)                           # Set position of axis (same as above)     

axis(side = 3,                         # Add another axis on top of plot
  at = c(seq(0, 10, by = 1.35)),       # Set another scale
  labels = c(seq(100, 170, by = 10)),  # Add labels
  padj = 1,                            # Adjust labels downward
  tcl = 1)                             # Put long tick marks into plot area

dev.off()                              # Output png file


# 14.6a Tick marks ======================================================= 14.6a

png(filename = "illustrations/fig-14-10-ticks-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(3.5, .25, .25, .25))       # Set margin sizes in inches

plot(myV1, myV2, type = "n",           # Setup w/no points & default x axis
  xlab = NA,                           # Turn off x axis label
  ylab = NA,                           # Turn off y axis label
  yaxt = "n",                          # Turn off y axis
  xlim = c(0, 10))                     # Set x axis range

axis(side = 1,                         # New x axis
  at = c(0:10),                        # Ticks at 0-10
  line = 3)                            # Move axis down to 3rd line

axis(side = 1,                         # New x axis
  at = c(seq(0, 10, by = 2)),          # Major ticks at 0-10 by 2
  labels = LETTERS[1:6],               # A-F as labels
  line = 6)                            # Put axis on 6th line

axis(side = 1,                         # New x axis
  at = c(seq(1, 10, by = 2)),          # Minor ticks at 1-10 by 2
  labels = NA,                         # Turn off labels for minor ticks
  line = 6)                            # Overlay axis on 6th line

axis(side = 1,                         # New x axis
  at = c(0:10),                        # Major ticks at 0-10 
  labels = c(1990:2000),               # Use years for labels
  las = 2,                             # Rotate labels to be perpendicular
  col = gray(.5),                      # Set main axis line to med gray
  tcl = -.75,                          # Major tick length at .75 below line
  col.tick = "black",                  # Make major ticks black
  lwd = 2,                             # Make major ticks longer
  line = 9)                            # Put axis on 9th line below plot

axis(side = 1,                         # Add overlay axis for the minor ticks
  at = c(seq(.5, 10, by = 1)),         # Minor ticks at every .5
  labels = NA,                         # No labels for minor ticks
  tcl = -.3,                           # Minor ticks length is .3 below line
  lwd = 0,                             # Turn off main axis line for overlay
  lwd.ticks = 1.25,                    # Set minor tick width to 1.25      
  col.tick = "darkgray",               # Color for minor tick marks 
  line = 9)                            # Overlay axis on 9th line

axis(side = 1,                         # New x axis
  at = c(0:10),                        # Major ticks at 0 - 10
  labels = NA,                         # Turn off labels
  tcl = -.5,                           # Major tick length at .5 below line
  lwd = 1.25,                          # Make major ticks thicker
  line = 13)                           # Put axis on 13th line

text(x = seq(0.3, 10.3, 1),            # x values for axis labels
  y = -46,                             # y value for axis labels
  xpd = TRUE,                          # Allow writing outside plot area
  labels = as.character(c(1990:2000)), # Years as text labels
  pos = 2,                             # Left align labels
  srt = 45)                            # Rotate strings 45 degrees

dev.off()                              # Output png file


# 14.6b Axes and Dates =================================================== 14.6b

dFormat = "%m/%d/%Y"                   # Set up a date format
myDate = as.Date(c("10/12/1947",       # Set up a date variable
  "5/14/1969", "7/2/1998", "1/3/2004", #  with several dates
  "11/24/2012"), dFormat)              #  using the format above
myV2 = c(14, 32, 7, 19, 11)            # Another simple variable

# A simple default time plot ---------------------------------------------------

png(filename = "illustrations/fig-14-11-dates.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(1, 1, .25, .25))

plot(myDate, myV2)                     # Basic plot with defaults

dev.off()                              # Output png file

# A customized time plot -------------------------------------------------------

png(filename = "illustrations/fig-14-12-dates-custom-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(1, 1, .25, .25))           # Set margins - no title

plot(myDate, myV2,                     # Customized plot
  xlim =                               # Set range for X axis
    c(as.Date("1/1/1940", dFormat),    # Starting date
    as.Date("12/31/2020", dFormat)),   # Ending date
  xaxt = "n",                          # Turn off X axis
  xlab = "Year")                       # Set X axis label

axis.Date(side = 1,                    # Set up new X axis w/ major tick marks
  at = seq.Date(                       # Create a sequence of dates
    as.Date("1/1/1940", dFormat),      # Starting point for sequence
    as.Date("12/31/2020", dFormat),    # Ending point for sequence
    by = "5 years"),                   # Increment value for sequence
  labels = seq(1940, 2020, by = 5),    # Labels for major tick marks
  las = 2)                             # Rotate labels perpendicular

axis.Date(side = 1,                    # Overlay X axis w/ minor tick marks
  at = seq.Date(                       # Create a sequence of dates
    as.Date("1/1/1940", dFormat),      # Starting point for sequence
    as.Date("12/31/2020", dFormat),    # Ending point for sequence
    by = "year"),                      # Increment value for sequence
  labels = NA,                         # Turn off labels
  tcl = -.25)                          # Set length at .25 below axis

abline(                                # Add a line 
  v=as.Date("10/23/1957", dFormat),    # Vertical placement on 10/23/1957
  col = "darkgray",                    # Set color
  lwd = 2)                             # Line width at 2

text(x = as.Date("1/1/1959", dFormat), # Label for the line - X coordinate
  y = 25,                              # Y coordinate
  pos = 4,                             # Put text to right of coordinates
  label = "October 23, 1957",          # Text for label
  cex = 1.5,                           # Set font size 50% bigger
  family = "mono",                     # Set font style
  font = 2)                            # Bold font

dev.off()                              # Output png file

# 14.7 Ad hoc text placement ============================================== 14.7

png(filename = "illustrations/fig-14-13-text.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, .25, .25))         # Set plot margins - no title

plot(x = 1.25, y = 1.5,                # Start plot with first point
  xlim = c(0, 3),                      # Set x range of plot
  ylim = c(0, 2),                      # Set y range of plot
  pch = 18,                            # Diamond shaped plotting symbol
  xlab = NA,                           # Turn off x axis label
  ylab = NA)                           # Turn off y axis label

points(1.5, 1, pch = 18)               # Add diamond shaped point
text(1.5, 1,                           # Add text at same position
  labels = "Defaults: No pos= or adj=")  

# Using the adj= option
points(.5, .25, pch = 18)              # Add diamond shaped point
text(.5, .25,                          # Add text at same point
  labels = "adj = c(1,1)",             # Text to add
  adj = c(1, 1))                       # Adjust position to lower left

text(.5, .25,                          # Add more text at same point
  labels = "adj = c(0,0)",             # Text to add
  adj = c(0, 0))                       # Adjust position to upper right

points(.5, .75, pch = 18)              # Add diamond shaped point
text(.5, .75,                          # Add text at same point
  labels = "adj = c(1,0)",             # Text to add
  adj = c(1, 0))                       # Adjust position to lower right

text(.5, .75,                          # Add text at same point
  labels = "adj = c(0,1)",             # Text to add
  adj = c(0, 1))                       # Adjust position to upper left

points(.5, 1.75, pch = 18)             # Add diamond shaped point
text(.5, 1.75,                         # Add text at same point
  labels = "adj = c(.5,.5) \n srt = 90",   
  srt = 90,                            # Rotate text 90 degrees
  adj = c(.5, .5))                     # Adjust position to center text
                                       #   (note this is also the default)

# Using the pos =  option 
points(1.25, 1.5, pch = 18)            # Add diamond shaped point
text(1.25, 1.5,                        # Add text at same point
  labels = "pos = 1",                  # Text to add
  pos = 1)                             # Set position to bottom centered (1)

text(1.25, 1.5,                        # Add text at same point
  labels = "pos = 2",                  # Text to add
  pos = 2)                             # Set position to left (2)

text(1.25, 1.5,                        # Add text at same point
  labels = "pos = 3",                  # Text to add
  pos = 3)                             # Set position to top centered (3)

text(1.25, 1.5,                        # Add text at same point
  labels = "pos = 4",                  # Text to add
  pos = 4)                             # Set position to right (4)

# Using xpd =  to go outside the plot area
text(.45, 0,                           # Add text at bottom of plot
  labels = "This uses xpd = TRUE to allow it to go outside the plot area",
  pos = 4,                             # Place text to right of point
  xpd = TRUE,                          # Set xpd = TRUE to allow
  font = 3)                            # Set font to italic

# plotmath expression
text(2.5, .75,                         # Add an expression w/plotmath
  labels = expression(Phi(italic(x))   # Build the expression
    == over(1, sigma * sqrt(2 * pi)) *
    italic(e)^ -over((x - mu)^2, 2 * sigma^2)),
  srt = 45,                            # Set at 45 degree angle
  cex = 1.25)                          # Increase size to 1.25

text(2.5, 1.75,                        # Add text for expression detail
  labels = "plotmath equation with \n srt = 45")

arrows(x0 = 2.5, x1 = 2.5,             # Add an arrow
  y0 = 1.5, y1 = 1.1,                  # y coordinates for arrow
  lwd = 3.5,                           # Set linewidth to 3.5
  col = "darkgray")                    # Set color to dark gray

dev.off()                              # Output png file

 

R Code for Chapter 15: Graphics IV — The Fun Stuff — Color, Shapes, and Lines

# ==============================================================================  
# Chapter 15 -- Graphics IV: The fun stuff -- Shapes
# ==============================================================================

# 15.1 Doing colors ======================================================= 15.1

# 15.1a Specifying colors ================================================ 15.1a

# Display all named colors
colors()

# A plot of normal deviates with colors ----------------------------------------

myV1 = seq(0, 1, by = .001)            # Set up some x values
myV2 = rnorm(myV1)                     # Y from random normal dist

# Here we will create a vector of integer values sorting myV2 which ranges
# between -4 and +4 into 8 values between 1 and 8.  We'll then use these
# to select colors from a palette of 8 colors

myV2colors = abs(round(2 * myV2, 0)) + 1    

# Here is the color version
png(filename = "illustrations/fig-15-1-colors.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(bg = gray(.9))                     # Set plot background to light gray
plot(myV1, myV2, type = "n",           # Setup plot without points
  ylim = c(-4, 4),                     # Set y range
  main =                               # Set title and subtitle
    "A color plot (in black and white)",  
  sub = "(Color version available online at www.sagepub.com/gaubatz)",
  col.lab = "red",                     # Color for axis labels
  col.axis = "blue",                   # Color for axis and ticks
  col.main = "darkblue")               # Color for main title
                      
rect(                                  # Create rectangle w/plot area coords
  par()$usr[1],                        # left x value at usr[1]
	par()$usr[3],                        # Right x value at usr[3]
	par()$usr[2],                        # Bottom y value at usr[2]
	par()$usr[4],                        # Top y value at usr[4]
  col = gray(.5),                      # Set rect color to medium gray
  lwd = 8,                             # Border with line width 8
  border = "red")                      # Set border color to red

myPalette = rainbow(8)                 # Create a palette of 8 colors 

points(myV1, myV2,                     # Add points to plot
  pch = 16,                            # Use solid circle
  cex = .5,                            # Set the points at half size
  col = myPalette[myV2colors])         # Set color based on myV2 value

dev.off()                              # Output png file

# Here is the grayscale version used in the book -------------------------------
png(filename = "illustrations/fig-15-1-colors-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(bg = gray(.9))                     # Set plot background to light gray
plot(myV1, myV2, type = "n",           # Setup plot without points
  ylim = c(-4, 4),                     # Set y range
  main =                               # Set title and subtitle
    "A color plot (in black and white)", 
  sub = "(Color version available online at www.sagepub.com/gaubatz)",
  col.lab = gray(.2),                  # Color for axis labels
  col.axis = gray(.4),                 # Color for axis and ticks
  col.main = gray(.1))                 # Color for main title
                      
rect(                                  # Create rectangle w/plot area coords
  par()$usr[1],                        # left x value at usr[1]
	par()$usr[3],                        # Right x value at usr[3]
	par()$usr[2],                        # Bottom y value at usr[2]
	par()$usr[4],                        # Top y value at usr[4]
  col = gray(.5),                      # Set rect color to medium gray
  lwd = 8,                             # Border with line width 8
  border = gray(.4))                   # Set border color to red

myPalette = gray.colors(8)             # Create a palette of 8 colors 

points(myV1, myV2,                     # Add points to plot
  pch = 16,                            # Use solid circle
  cex = .5,                            # Set the points at half size
  col = myPalette[myV2colors])         # Set color based on myV2 value

dev.off()                              # Output png file

# 15.1b Color transparency =============================================== 15.1b

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

par(mar = c(0, 0, 0, 0))               # Set all margins to 0
plot.new()                             # New plot

abline(h = .5,                         # Add a horizontal line at .5
  lwd = 4)                             # Set line width to 4

segments(                              # Add segments w/ degrees of transparency
  x0 = seq(.1, .9, by = .15),          # The first x values for the lines
  y0 = .1,                             # The first y values for the lines
  x1 = seq(.1, .9, by = .15),          # The second x values
  y1 = .9,                             # The second y values
  col = c("#00000010", "#00000025",    # Black w/increasing opacity
    "#00000050", "#000000A5",
    "#000000D0", "#000000FF"),
  lwd = 40)                            # Line width = 40

text(                                  # Black labels for degree of opacity
  x = seq(.1, .9, by = .15),           # x values
  y = .1,                              # y value
  labels =                             # Text to show alpha channel values
    c("10", "25", "50", "A5", "D0", "FF"))    

text(                                  # White labels for degree of opacity
  x = seq(.1, .9, by = .15),           # x values
  y = .9,                              # y value
  col = "white",                       # Set color to white
  labels =                             # Text to show alpha channel values
    c("10", "25", "50", "A5", "D0", "FF"))    

dev.off()                              # Output png file


# 15.2 Custom points ====================================================== 15.2

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

par(mai = c(0, 0, 0, 0))               # No space around plot

plot(x = 0, y = 0,                     # Set up an empty plot
  xlim = c(0, 9), ylim = c(0, 14),     # Set x and y lengths
  type = "n",                          # Suppress points
  xaxt = "n", yaxt = "n",              # Suppress axis marks
  xlab = "", ylab = "")                # Suppress axis labels

points(x = c(rep(3, 13),rep(7, 13)),   # Add points in 2 cols (x = 3 & 7)
  y = c(c(13:1), c(13:1)),             # Increment y values for the 2 cols
  pch = c(0:25),                       # Run through 25 values for pch
  cex = 1.5)                           # Increase size to 1.5

text(x = c(rep(2, 13),rep(6, 13)),     # Add text labels also in 2 cols
  y = c(c(13:1), c(13:1)),             #  with incremented y values
  labels =                             # Label each point with 
    paste(as.character(c(0:25)),       #  the appropriate numeric
    " = "))                            #  value.

dev.off()                              # Close png device to output plot

# Plotting other symbols: Alphanumerics ----------------------------------------

                                       # Output a png file
png(filename = "illustrations/fig-15-4-pch-letters.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(1, 1, .25, .25))           # Set plot margins - no title

plot(x = c(1:4), y = c(2, 4, 3, 4),    # Plot some x & y values
  pch = c("g", "&", "3", "H"),         # Assign alphanumerics to each point
  cex = 2,                             # Scale symbols to double size
  xlim = c(0, 5), ylim = c(0, 5),      # Set range of plot
  xlab = "X", ylab = "Y")              # Set axis labels

dev.off()                              # Close png device to output plot

# 15.2a Connectors ======================================================= 15.2a

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

layout(matrix(c(1:12),                 # Setup a layout matrix
  ncol = 4,                            #   with 4 columns & 3 rows
  byrow = T),                          #   to fill by row.
  heights = c(.45, .45, .1),           # Relative heights
  widths = c(.05, .3, .3, .3))         # Relative widths

layout.show(12)                        # Show the layout

par(mai = c(.1, .1, .5, .1))           # Set margins 
plot.new()                             # Skip the first grid location
plot(x = c(1:4), y = c(2, 4, 3, 4),    # Plot some x & y values
  type = "p",                          # Set connectors to just points
  xlim = c(0, 5), ylim = c(0, 5),      # Set range of plot
  xaxt = "n",                          # Turn off x axis
  xlab = NA, ylab = NA,                # Turn off axis labels
  main = "type = 'p'")                 # Add main title

plot(x = c(1:4), y = c(2, 4, 3, 4),    # Plot some x & y values
  type = "l",                          # Set connectors to just lines
  xlim = c(0, 5), ylim = c(0, 5),      # Set range of plot
  xaxt = "n", yaxt = "n",              # Turn off axes
  xlab = NA, ylab = NA,                # Turn off axis labels
  main = "type = 'l'")                 # Add main title
    
plot(x = c(1:4), y = c(2, 4, 3, 4),    # Plot some x & y values
  type = "b",                          # Set connectors to both lines & points
  xlim = c(0, 5), ylim = c(0, 5),      # Set range of plot
  xaxt = "n", yaxt = "n",              # Turn off axes
  xlab = NA, ylab = NA,                # Turn off axis labels
  main = "type = 'b'")                 # Add main title
    
plot.new()                             # Skip the 5th layout space
plot(x = c(1:4), y = c(2, 4, 3, 4),    # Plot some x & y values
  type = "s",                          # Set connectors to stair steps
  xlim = c(0, 5), ylim = c(0, 5),      # Set range of plot
  xlab = NA, ylab = NA,                # Turn off axis labels
  main = "type = 's'")                 # Add main title

plot(x = c(1:4), y = c(2, 4, 3, 4),    # Plot some x & y values
  type = "h",                          # Set to histogram-style vertical lines
  xlim = c(0, 5), ylim = c(0, 5),      # Set range of plot
  yaxt = "n",                          # Turn off y axis
  xlab = NA, ylab = NA,                # Turn off axis labels
  main = "type = 'h'")                 # Add main title
    
plot(x = c(1:4), y = c(2, 4, 3, 4),    # Plot some x & y values
  type = "n",                          # Turn off points
  xlim = c(0, 5), ylim = c(0, 5),      # Set range of plot
  yaxt = "n",                          # Turn off y axis
  xlab = NA, ylab = NA,                # Turn off axis labels
  main = "type = 'n'")                 # Add main title
    
    
dev.off()                              # Close png device to output plot

# 15.2b The symbols() approach =========================================== 15.2b
                                       # Output a png file
png(filename = "illustrations/fig-15-6-symbols-BW.png",
  units = "in",                        # Set measurements in inches
  res = 1200,                          # Set resolution at 1200dpi
  width = 6,                           # Width at 6 inches
  height = 4)                          # Height at 6 inches

par(mai = c(1, 1, .25, .25))

symbols(x = c(1:3), y = c(2, 4, 3),    # Set up some X and Y values
  circles = c(1, 2, 1.5),              # Circle radii
  bg = gray.colors(3),                 # Circle colors from gray palette
  xlim = c(0,5), ylim = c(0,5),        # Set range of plot
  xlab = "X", ylab = "Y")              # Set axis labels

myRect = rbind(c(1.5, .75),            # Set widths for 2 rectangles
  c(.75, 2))                           # Set heights for 2 rectangles

symbols(x = c(2, 4), y = c(2, 3),      # 2nd symbol plot X & Y coords
  add = TRUE,                          # Overlay on previous plot     
  rectangles = myRect,                 # Add rectangles
  bg = c("lightgray", "darkgray"))     # Rectangle colors      

dev.off()                              # Close png device to output plot

# 15.3 Adding Lines ======================================================= 15.3

png(filename = "illustrations/fig-15-7-line types.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(0, 0, 0, 0))               # Set for no margins

plot.new()                             # Start a plot
  
segments(                              # Add segments w/ degrees of transparency
  x0 = .1,                             # The first x values for the lines
  y0 = seq(.9, .1, -.16),              # The first y values for the lines
  x1 = .6,                             # The second x values
  y1 = seq(.9, .1, -.16),              # The second y values
  lty = c(1:6),                        # A vector of line types
  lwd = 2)                             # Line width = 2


text(                                  # Add labels 
  x = .65,                             # x values
  y = seq(.9, .1, -.16),               # y value
  pos = 4,                             # Text to right of point
  cex = 1.25,                          # Text size
  label = c("lty = 1 or 'solid'",      # The set of labels
    "lty = 2 or 'dashed'",             
    "lty = 3 or 'dotted'",
    "lty = 4 or 'dotdash'",
    "lty = 5 or 'longdash'",
    "lty = 6 or 'twodash'"))
 
dev.off()                              # Output png file

# 15.3a Basic lines ====================================================== 15.3a

myV1 = c(1, 2, 4, 5, 8)                # Some data to work with
myV2 = c(1.5, 3, 2, 7, 6)

png(filename = "illustrations/fig-15-8-lines-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(mar = c(4.2, 4, 1, 1))             # Set margin widths in lines

plot(myV1, myV2,                       # A simple default scatterplot
  pch = 19, col = "darkgray",          # Solid point markers in darkgray
  xlim = c(0, 10), ylim = c(0, 10))    # Set range for x & y axes

# Line 1 - a horizontal dashed line
abline(h = 1.5,                        # Add a horizontal line at y = 1.5
  lwd = 3,                             # Give it a width of 3     
  lty = 2,                             # Dash it all
  col = gray(.4))                      # Make it medium gray     

text(x = 8, y = 2.2,                   # Add label for line 1
  label = "Line 1",                    # Label text
  cex = 2,                             # Set size to 2
  col = gray(.4))                      # Set color to gray .4

# Line 2 - a vertical line with long dashes
abline(v = 4,                          # Add a vertical line at x = 4
  lwd = 8,                             # Give it a width of 8     
  lty = "longdash",                    # Use long dashes
  col = gray(.7))                      # Make it light gray     

text(x = 3.5, y = 6,                   # Add label for line 2
  label = "Line 2",                    # Label text
  cex = 2,                             # Set size to 2
  srt = 90,                            # Rotate text to vertical
  col = gray(.7))                      # Set color to light gray

# Line 3 - abline using coefficients
abline(a = 3.2,                        # Add a line w/ intercept = 3.2
  b = 1.5,                             #   and slope = 1.5
  lwd = .5,                            # Give it a width of .5     
  col = gray(.2))                      # Make it dark gray     

text(x = 1.5, y = 6.5,                 # Add label for line 3
  label = "Line 3",                    # Label text
  cex = 2,                             # Set size to 2
  srt = 44,                            # Rotate text
  col = gray(.2))                      # Set color to dark gray

# Line 4 - Line segment
lines(x = c(6, 12),                    # x values for line segment
  y = c(11, 4),                        # y values for line segment
  lty = 4,                             # Dot-dash pattern
  col = gray(.1),                      # Make it dark gray
  lwd = 2,                             # Set line width at 2
  xpd = TRUE)                          # Allow outside plot area

text(x = 8, y = 9.75,                  # Add label for line 4
  label = "Line 4",                    # Label text
  cex = 2,                             # Set size to 2
  srt = -34,                           # Rotate text
  col = gray(.1),                      # Set color to dark gray
  xpd = TRUE)                          # Allow to extend beyond plot

# Line 5 - A regression line 
myReg = lm(myV2 ~ myV1)                # A simple regression model
                                       
abline(reg = myReg,                    # Use regression model to define line
  col = "black")                       # Set color

text(x = 6, y = 6,                     # Add label for line 5
  label = "Line 5",                    # Label text
  cex = 2,                             # Set size to 2
  srt = 23,                            # Rotate text
  col = "black")                       # Set color

dev.off()                              # Output the png file


# 15.3b Data-based line segments ========================================= 15.3b

myV1 = c(1, 2, 4, 5, 7, 8, 9)          # Some data to work with
myV2 = c(2, 3, 2, 7, 6, 8, 6)

myReg = lm(myV2 ~ myV1)                # A quick regression model                       

png(filename = "illustrations/fig-15-9-line-segments-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(1, 1, .25, .25))           # Set margin widths in inches

plot(myV1, myV2,                       # The scatter plot
  pch = 19,                            # Solid point markers
  xlim = c(0, 10), ylim = c(0, 10))    # Set range for x & y axes

abline(reg = myReg)                    # Use regression model to define line

segments(x0 = myV1, x1 = myV1,         # Add line segments from observed
  y0 = myV2, y1 = myReg$fitted.values) #  to fitted values

# Add model equation text to plot
# First paste together the model text
myModel = paste(                       # Paste together reg model as text
  "Model: ",                             
  names(myReg$model)[1],               # Get dependent variable
  " = ",                              
  round(myReg$coefficients[1], 2),     # Get y intercept coefficient
  " + ",
  round(myReg$coefficients[2], 2),     # Get slope coefficient
  names(myReg$model)[2],               # Get independent variable
  sep = "")                            # No space between paste elements    

text(x = 10, y = 1.5,                  # Add model to plot
  label = myModel,                     # The model as text 
  pos = 2)                             # Right side alignment

# Get the R-squared value from the summary function
myR2 = round(summary(myReg)$r.squared, 2)

# Add the R-squared value to the plot
text(x = 10, y = .5,                   # Add R-squared value to plot
  label = bquote(R^2 == .(myR2)),      # Use bquote to paste elements
  pos = 2)                             # Right side alignment

dev.off()                              # Output the png file


# 15.3c Arrows =========================================================== 15.3c 

# A solid arrowhead function
# 
# This function draws an arrow from (x0,y0) to (x1,y1) with a solid
# arrowhead. 
#
# The default arrowhead length is .25 inches. 
# The default angle of the arrowhead edges is 30 degrees.
# The other parameters are standard for line and polygon formatting.
#
# The basic logic here is to use matrix rotation to translate the arrowhead
# coordinates.
#
# Note that R's trigonometric functions work with radians rather than degrees
#
myArrow = function(x0, y0, x1, y1,     # Set up arrow function ----------------+
  L = .25,                             # Default arrowhead length              |
  angle = 30,                          # Default angle of arrowhead            |
  code = 2,                            # Default arrowhead at x1,y1            |
  col = par("fg"),                     # Default color                         |
  ljoin = par("ljoin"),                # Default line joint style (0)          |
  lty = par("lty"),                    # Default line type                     |
  lwd = par("lwd"),                    # Default line width                    |
  xpd = FALSE){                        # Default stay within plot area         |
                                       # Start function code                   |
    if(code == 1){                     # Reverse arrow direction               |
      tmp = x1; x1 = x0; x0 = tmp      # Switch x values                       |
    }                                  #                                       |
    if(code == 1){                     #                                       |
      tmp = y1; y1 = y0; y0 = tmp      # Switch y values                       |
    }                                  #                                       |
#                                                                              |
# We need to control for the aspect ratio or for different x,y scales          |
#   in setting up the arrow heads. We'll do that by translating the            |
#   usr parameter setting from the original x,y units to units based           |
#   on the plot dimensions measured in inches.  This will allow us to          |
#   adjust the angles to account for different x and y scales. Note,           |
#   however, that rescaling the plot after it is drawn will distort            |
#   the arrowheads.                                                            |
#                                                                              |
    X0 = (x0 - par()$usr[1])/(par()$usr[2] - par()$usr[1]) * par()$fin[1]  #   |
    Y0 = (y0 - par()$usr[3])/(par()$usr[4] - par()$usr[3]) * par()$fin[2]  #   |
    X1 = (x1 - par()$usr[1])/(par()$usr[2] - par()$usr[1]) * par()$fin[1]  #   |
    Y1 = (y1 - par()$usr[3])/(par()$usr[4] - par()$usr[3]) * par()$fin[2]  #   |
#                                                                              |    
    oldusr = par("usr")                # Save original usr settings            |
    par(usr = c(0, par("fin")[1],      # Set up new usr settings based         |
              0, par("fin")[2]))       #  on plot dimensions in inches         |
#                                                                              |
    t = angle * pi/180                 # Convert angle degrees to radians      |
    slope = (Y1 - Y0)/(X1 - X0)        # Calculate slope of line               |
    S = atan(slope)                    # Slope angle in radians                |
                                       #                                       |
    M = ifelse(X1 < X0, -1, 1)         # Set a marker for X1 < X0              |
                                       # Set length of vector XA               |
    XA = sqrt((X1 - X0)^2 + (Y1 - Y0)^2)                                   #   |
#                                                                              |
# Get arrowhead vertices from rotated vectors                                  |
    XC = X0 + M * ((XA - L) * cos(S) + L * tan(t) * sin(S))                #   |
    YC = Y0 + M * ((XA - L) * sin(S) - L * tan(t) * cos(S))                #   |
    XB = X0 + M * ((XA - L) * cos(S) - L * tan(t) * sin(S))                #   |
    YB = Y0 + M * ((XA - L) * sin(S) + L * tan(t) * cos(S))                #   |
#                     |                                                        |
# Draw arrow line stopping at beginning of the arrowhead                       |
    lines(x = c(X0, X1 - M * L * cos(S)),                                  #   |
      y = c(Y0, Y1 - M * L * sin(S)),                                      #   |
      lty = lty, lwd = lwd,            # Apply line format options             |
      col = col, xpd = xpd,            #                                       |
      ljoin = ljoin)                   #                                       |
    polygon(x = c(X1, XB, XC),         # Draw arrow head                       |
      y = c(Y1, YB, YC),               #  at vertices                          |
      col = col,                       # Apply format options                  |
      border = col,                    #                                       |
      xpd = xpd)                       #                                       |
    par(usr = oldusr)                  # Reset to original usr settings        |
}                                      # End of myArrow function --------------+

# A plot of arrows 
png(filename = "illustrations/fig-15-10-arrows-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(.5, .5, .25, .25))         # Set margin widths in lines

plot(x = 0, y = 0, type = "n",         # Set up a blank plot
  xlim = c(0, 5), ylim = c(0, 5),      # Define x and y range
  xlab = "", ylab = "")                # Turn off axis labels

# Diverse arrows
arrows(x0 = 3, y0 = 4.25, x1 = 5, y1 = .25, 
  length = 1, angle = 15, lwd = 2)
arrows(x0 = 1.25, y0 = 1, x1 = 3.25, y1 = .75, 
  col = "darkgray", code = 3)
myArrow(x0 = 0, y0 = 1.5, x1 = 3.5, y1 = 4.5, 
  col = "black")
myArrow(x0 = 1, y0 = .5, x1 = 4.5, y1 = 0, 
  col = gray(.6)) 
myArrow(x0 = 4, y0 = 3.5, x1 = 1, y1 = 1.5, L=.5, 
  col = gray(.4), lwd = 2)
myArrow(x0 = 2.5, y0 = 1.25, x1 = 1, y1 = 4.2, 
  col = gray(.5), lwd = 4)
myArrow(x0 = 6, y0 = 5, x1 = 4, y1 = 3, 
  col = "gray", lwd = 8, angle = 20, L=.75, xpd = T)
myArrow(x0 = 0, y0 = 5, x1 = 4, y1 = 5, 
  col = "gray", lwd = 3, angle = 40, code = 1)  
myArrow(x0 = .5, y0 = .5, x1 = 4, y1 = 1.5, 
  col = "darkgray", lwd = 1, angle = 20, L=.1)

dev.off()                              # Output png file


# 15.3d Grid lines ======================================================= 15.3d

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

layout(matrix(c(1, 1, 2, 3),           # Set layout of 3 plots
  ncol = 2,                            #  organized as 2 columns
  byrow = T))                          #  and filled by row.

par(mai = c(.5, .5, .5, .25))          # Set the margin sizes

plot(0:10, pch = 19,                   # Plot 1 w/solid dots
  main = "Horizontal Lines",           # Title for plot 1
  xlab = NA, ylab = NA,                # Turn off axis labels
  yaxs = "i")                          # Eliminate y axis overage

grid(nx = NA,                          # Create a grid w/o verticals
  ny = 5,                              #  and 5 horizontal partitions
  lty = 1,                             # Set line type to solid
  lwd = 2,                             # Set line width to 2
  col = "gray")                        # Set color

points(0:10, pch = 19)                 # Redo points on top of grid

plot(0:10, pch = 19,                   # Plot 2 w/solid dots
  main = "Default Grid",               # Title for plot 2
  xlab = NA, ylab = NA)                # Turn off axis labels

grid()                                 # Add default grid on tick marks
                                       
par(mai = c(0, 0, 0, 0))               # Set margins to zero
   
plot(0:10, type = "n", yaxt = "n")     # Create an empty plot
grid(nx = 10, ny = 10,                 # Add gridlines
  lty = 1,                             # Use solid lines
  col = "black")                       # Set color to black

par(usr = c(0, 1, 0, 1))               # Use usr par
text(.5, .55,                          # Add text at center
  labels = "An empty grid",            # Text to add
  cex = 2)                             # Set text size at 2

dev.off()                              # Output png file

# 15.4 Shapes ============================================================= 15.4

# Some demonstration polygons

myX1 = c(1, 2, 3, 6, 7, 8)             # Set up some coordinates to work with
myY1 = c(2, 8, 4, 4, 6, 3)
myX2 = seq(1, 3, by = .001)
myY2 = 9 - (2 - myX2)^2
myX2 = c(1, myX2, 3)
myY2 = c(7, myY2, 7)

png(filename = "illustrations/fig-15-12-polygons-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(.5, .5, .25, .25))         # Set margin widths in inches

plot(x = 0, y = 0, type = "n",         # Set up a blank plot
  xlim = c(0, 10), ylim = c(0, 10),    # Define x and y range
  xlab = "", ylab = "")                # Turn off axis labels

polygon(x = c(4, 4, 8, 8),             # Set x & y values for rectangle 
  y = c(1, 2, 2, 1),     
  col = gray(.7))                      # Fill color

polygon(x = c(6, 6, 9, 9),             # Set x & y values for rectangle
  y = c(6, 8, 8, 6),    
  border = gray(.2),                   # Add a dark gray border
  lwd = 4,                             # Line width 4 for border
  col = gray(.9))                      # Light gray fill for rectangle

polygon(myX2, myY2,                    # A polygon using preset points
  lwd = 2, lty = 2, border = "black",  # Dashed border with line width 2
  col = gray(.3))                      # Fill color

polygon(myX1, myY1,                    # A polygon with preset points
  border = gray(.1),                   # Border color
  lwd = 3,                             # Border & shading width = 3
  density = 10,                        # Shading density = 10 lines/inch
  angle = 135,                         # Shading line angle = 135 degrees
  col = gray(.6))                      # Color of shading lines


dev.off()                              # Output png file

# A more complex shapefile -----------------------------------------------------

# California Shapefile Read
# This reads in the coordinates for the shape of California, extracted from
# a google earth kml file.

# Note that the location of this datafile will change to somewhere on the 
# www.sagepub.com/gaubatz site

CAshape = read.csv(
  file = "http://www.kktg.net/R/calif-coords.csv", header = FALSE)

summary(CAshape)                       # Show structure & range of coordinates

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

par(mai = c(0, 0, 0, 0))               # no margins

plot(x = 0, y = 0, type = "n",         # Set empty plot
  xlim = c(-125, -113),                # X range
  ylim = c(32, 43),                    # Y range
  axes = FALSE,                        # Turn off axes
  xlab = NA, ylab = NA)                # Turn off labels

polygon(x = CAshape$V1,                # Set x & y values from CA coordinates
  y = CAshape$V2, 
  col = gray(.8))                      # Fill color

text(x = -117, y = 39.5,               # Position label
  label = "California",                # Label text
  cex = 2.5)                           # Set size to 2.5

dev.off()                              # Output png file

# This routine draws a two-sided hypothesis test -------------------------------

options(scipen = 6)                    # Stop sci notation if <6 dec places

# Provided Values
mean1 = 3.35                           # First sample mean
mean2 = 3.09                           # Second sample mean
sd1 = 1.24                             # First sample std deviation
sd2 = 1.21                             # Second sample std deviation
n1 = 142                               # First sample size
n2 = 126                               # Second sample size

# Calculated Values

seBlend = sqrt(sd1^2/n1 + sd2^2/n2)    # Blended std. error
dMeans = max(mean1, mean2) -           # Calculate difference in means 
  min(mean1, mean2)
z = (dMeans)/seBlend                   # Calculate z score
rangeZ = ceiling(abs(z)) + 2           # Set range for x values
rangeZ = ifelse(rangeZ < 4, 4, rangeZ) # Set minimum range of +/- 4

# Hypothesis test results
p = 2 * (1 - pnorm(z))                 # p value for 2 sided z-test
ptext = round(p, 2)                    # Version of p for annotation
OneMinusP = round(1 - p, 2)            # Version of 1 - p for annotation

# Graphing values
X1 = seq(-rangeZ, rangeZ, by = .001)   # Set up sequence of x values
Y1 = dnorm(X1)                         # Set up t curve values for each x
X2 = X1                                # Second x to use for filling curve
Y2 = Y1                                # Second y to use for filling curve
cd = data.frame(X1, Y1, X2, Y2)        # Join in data frame

png(filename = "illustrations/fig-15-14-normal-curve-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(1, 1, .25, .25))           # Set margin - no title


# Plot components
plot(cd$X1, cd$Y1,                     # Plot normal distribution
  type = "l", lwd = 2,                 # Line plot with linewidth =2
  ylim = c(0, .5),                     # Set range for y axis
  xlab = "z-score",                    # Add x axis label
  ylab = "Probability",                # Add y axis label
  yaxs = "i")                          # Eliminate y axis overage


abline(h = 0)                          # Horizontal boundary line at y = 0

lines(x = c(z, z), y = c(0, .43))      # Add short vertical line at z
lines(x = c(-z, -z), y = c(0, .43))    # Add short vertical line at -z    

# Set up borders of shaded regions
xz1 = which(
  cd$X1 == max(cd$X1[cd$X1 < z]))      # Find x just to left of z
cd$Y2[xz1] = 0                         # Set y for that x to 0      
cd$X2[xz1] = cd$X2[xz1 - 1]            # Shift max x over for vertical line
xz2 = which(
  cd$X1 == min(cd$X1[cd$X1 > -z]))     # Find x just to right of -z
cd$Y2[xz2] = 0                         # Set y for that x to 0      
cd$X2[xz2] = cd$X2[xz2 + 1]            # Shift max x over for vertical line

xz3 = which(
  cd$X1 == min(cd$X1[cd$X1 > z]))      # Find x just to right of z
cd$Y2[xz3] = 0                         # Set y for that x to 0      
cd$X2[xz3] = cd$X2[xz3 + 1]            # Shift max x over for vertical line

xz4 = which(
  cd$X1 == max(cd$X1[cd$X1 < -z]))     # Find x just to left of -z
cd$Y2[xz4] = 0                         # Set y for that x to 0      
cd$X2[xz4] = cd$X2[xz4 - 1]            # Shift max x over for vertical line
    
# Do shading
polygon(cd$X2[cd$X1 < z & cd$X1 > -z], # Fill for center region
  cd$Y2[cd$X1 < z & cd$X1 > -z],
  col = "light gray")                  # Set color
  
polygon(cd$X2[cd$X1 < -z],             # Fill for left tail 
  cd$Y2[cd$X1 < -z], 
  col = "darkgray")                    # Set color
  
polygon(cd$X2[cd$X1 > z],              # Fill for right tail 
  cd$Y2[cd$X1 > z],
  col = "darkgray")                    # Set color

abline(v = 0)                          # Vertical line at x = 0    

# Add labels
text(x = z, y = .42, pos = 4,          # Add label showing z-score 1
  labels = paste("z = +", round(z, 2)))
  
text(x = -z, y = .42, pos = 2,         # Add label showing z-score 2
  labels = paste("z = -", round(z, 2)))  

label1 = paste(                        # Annotation for area under curve
  "Area under curve\nbetween z values = ", 
  OneMinusP)
  
label2 = paste(                        # Annotation for area in tails
  "Area under curve\nin both tails = ",
  ptext)

text(x = -rangeZ/1.4, y = .2,          # Add label for main pr region
  labels = label1,                     # Use text created above
  cex = .75)                           # Font size 
  
arrows(x0 = -rangeZ/1.4, x1 = -z/2,    # Arrow from text to main pr region
  y0 = .17, y1 = .1,
  length = .15)                        # Set arrowhead size
  
text(x = rangeZ/1.4, y = .2,           # Add label for tails
  labels = label2,                     # Use label created above
  cex = .75)                           # Set text size

arrows(x0 = z + (rangeZ - z)/2,        # Add arrow from text to tails label
  y0 = .17,      
  y1 = .02,
  length = .15)
  
dev.off()                              # Output the png file

# 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


# 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