In the last post, I demonstrated how to produce a matrix plot in R. As I mentioned before, I have used matrix plots to display data that was chronologically ordered. When I first started using time series data, one of the major hurdles to plotting was getting date labels looking right and also getting them in the right location. Here I’ll show you my method for using date labels on either axis of a x-y plot. As usual, I find the R help forums very using for times when I am stumped. There are some excellent tips, examples and discussions about everything to do with R. I will use a simple example with random data points, and plot dates on the x-axis. Also, if you look carefully, you’ll see a method for converting between MS excel time and the time format from the “chron” pacakage. I also added a few tweeks I like to use to “spruce up” my figures:

– Have axis tick mark inside plot region

– Use mtext() to plot axis labels

– Add grid to background for easier viewing.

# Plotting parameters par(font = 2, mar=c(5.5, 4, 3, 4) + 0.1) # Create chron object (dates) from excel times library(chron) excel.dates <- seq(40179, 40205, 1) #time in MS excel (1/1/2010 to 1/27/10) orig <- chron("12/30/1899") date <- orig + excel.dates; # Y data y.dat <- rnorm(27, 10, 3) # Plot it up! Don't add annotations or axes for now plot(date, y.dat, type="n", ann=F, axes=F) # Add grid to background of plot abline(h = seq(0, max(y.dat)+4, 2), col = "grey90", lty= 3) abline(v = c(seq(date[1], date[length(date)],2)), col = "grey90", lty= 3) # Add data lines(date, y.dat, lwd = 2, col = "black") points(date, y.dat, pch = 20, col = "magenta") box() # add box around plot # Add X-Axis and label axis.Date(1,date,format="%m/%d/%y", labels = F, at=c(seq(date[1], date[length(date)],2)), tck = +0.01) label=c(seq(date[1], date[length(date)],2)) x.len=length(label) text(x=label[1:x.len], par("usr")[3]-.235, srt = 45, adj = 1, labels = label, xpd = T) mtext(side = 1, "Time", line = 3.2) #X-axis label # Add Y-axis and label axis(2, at =seq(0, max(y.dat)+4, 2), las = 2, tck = +0.01) mtext(side = 2, "Y Var", line = 3.0) #Y-axis label