Figure 14-1: Various Text

Portfolio Categories: All Graphics and SGR Book Graphics.

Demonstration of text effects in R graphics

Various Text Effects with Basic R Graphics


# 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