Figure 14-12: A Custom Date Axis

Portfolio Categories: All Graphics and SGR Book Graphics.

A Custom Date Axis with R Graphics

A Custom Date Axis


# 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