[R] Time line plot in R?

Jim Lemon bitwrit at ozemail.com.au
Wed Jan 19 23:15:50 CET 2005


Sander Oom wrote:
> Dear R users,
>
> In order to illustrate the possible effects of events on variables
> plotted against time, I would like plot a time line of events along side
> the plot of the variables.
>
> The x-axis should be some time unit; the y-axis should be the variable
> of interest; the time line should be plotted below the graph along the
> same x-axis scale.
>
> As I have many variables and different events lists, I would like to
> write a script to read the events from a file and plot them together
> with the other plot.
>
> The time line should look something like this:
> http://www.oslis.k12.or.us/secondary/howto/organize/images/timeline.gif
>
Here's one way:

# some fake data please, maestro
fakedata<-sample(1:10,10)
# leave a bit of extra space beneath and to the left of the plot
par(mar=6,6,4,2)
# this function will probably end up in the "plotrix" package
time.line<-function(x,y,at=NULL,labels=TRUE,tlticks=NULL,...) {
 if(missing(x) && missing (y))
  stop("Usage: time.line(x,y,at=NULL,labels=TRUE)")
 plotrange<-par("usr")
 # get the graphical parameters
 oldpar<-par(no.readonly=TRUE)
 # turn off clipping
 par(xpd=TRUE)
 if(missing(x)) {
  # it's a horizontal line
  segments(plotrange[1],y,plotrange[2],y,...)
  ticklen<-(plotrange[4]-plotrange[3])*0.02
  if(!is.null(tlticks))
   segments(tlticks,y+ticklen,tlticks,y-ticklen,...)
  mwidth<-strwidth("M")
  # blank out the line where labels will appear
  rect(at-mwidth,y-ticklen,at+mwidth,y+ticklen,col="white",border=FALSE)
 # rotate the text
  par(srt=90)
  # draw the labels
  text(at,y,labels,...)
 }
 if(missing(y)) {
  # it's a vertical line
  # draw the line
  segments(x,plotrange[3],x,plotrange[4],...)
  ticklen<-(plotrange[2]-plotrange[1])*0.02
  if(!is.null(tlticks))
   segments(x+ticklen,tlticks,x-ticklen,tlticks,...)
  mheight<-strheight("M")
  # blank out the line where labels will appear
  rect(x-ticklen,at-mheight,x+ticklen,at+mheight,col="white",border=FALSE)
  # draw the labels
  text(x,at,labels,...)
 }
 # restore the parameters
 par(oldpar)
}
# create a file with the positions and labels you want like this:
# 2.5,first
# 4,second
# 7,third
# 8.5,fourth
# call it "labels.txt" and read it in
tl.labels<-read.table("labels.txt",sep=",")
plot(fakedata,xlab="")
# display a horizontal time line
time.line(x=-1,at=tl.labels[[1]],labels=tl.labels[[2]],col="black")
# now a vertical one
time.line(y=-1,at=tl.labels[[1]],labels=tl.labels[[2]],col="black")




More information about the R-help mailing list