Figure 15-9: Adding Line Segments

Portfolio Categories: All Graphics and SGR Book Graphics.

Adding Lines Systematically to an R Plot

Adding Lines Systematically to an R plot


# 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