Figure 15-12: Drawing Polygons

Portfolio Categories: All Graphics and SGR Book Graphics.

Drawing Polygon Shapes with R Graphics

Drawing Polygon Shapes with R Graphics


# 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