Figure 13-3: R Plot Coordinates

Portfolio Categories: All Graphics and SGR Book Graphics.

Demonstration of plot coordinates with R Graphics

R Graphics with Plot Coordinates


# 13.4 Graphic coordinates ================================================ 13.4

# Regular x,y coordinates
myX = c(0:20)                          # Create x var that runs 0 to 20
myY = myX * .5                         # Create y var that runs 0 to 10

png(filename = "illustrations/fig-13-3-placed objects.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 margins - no title

plot(myX, myY, type = "n")             # Plot x & y, but suppress points
text(x = 15, y = 6, "Hello World!")    # Add text at x = 15 and y = 6
polygon(x = c(7, 15, 15, 7),           # Add a rectangle at x coords
  y = c(1, 1, 3, 3))                   #   and y coords
points(x = c(5, 18), y = c(6, 1),      # Add a dashed line between points 
  type = "l", lty = 2)                 #  at given x and y coordinates.     

xtext = "x coordinates 0-20"           # Some text for adding to plot
ytext = "y coordinates 0-10"           # Some more text for plot    

arrows(x0 = 6, y0 = 8, x1 = 0,         # Add a horizontal arrow
  lwd = 2)                             #   Set line width to 2
text(x = 10, y = 8, xtext)             # Add coordinates text
arrows(x0 = 14, y0 = 8, x1 = 20,       # Add another horizontal arrow
  lwd = 2)                             # Set line width to 2

arrows(x0 = 4, y0 = 2, y1 = 0,         # Add a vertical arrow
  lwd = 2)                             # Set line width to 2
text(x = 4, y = 5, ytext, srt = 90)    # Add rotated y coordinates text
arrows(x0 = 4, y0 = 8, y1 = 10,        # Add another vertical arrow
  lwd = 2)                             # Set line width to 2

dev.off()                              # Output png