# Annotating graphs produced in R

Figures and graphs that I save in my R session are usually for my documentation, and I would like to annotate them with working directory, file name and date. Since I need to hardcopy my documentation (don’t ask), that would make my life easier. I was thinking that I could modify the pdf’s before printing, but I actually prefer to have the figures stamped directly in R.

Since most of the time I generate graphics with dev.copy2pdf(), I concocted the following little function:

# annotate PDF copy of the graph produced
copyan <- function( file= "tmp.pdf", cex= 0.75 ) {

oldpar <- par( mar= c( 0, 0, 0, 0 ), usr= c( 0, 1, 0, 1 ) )
on.exit( par( oldpar ) )

par( new= TRUE )
plot.new()

# ann is the annotation stamp:
# current working directory,
# file name, date and time.
ann <- paste( getwd(), file, Sys.time(), sep= ", " )
strh <- strheight( ann, cex= cex )
strw <- strwidth(  ann, cex= cex )

# put text in the lower bottom corner,
# just at the very margin of the plot
usr1 <- par( "usr" )
text( usr1[1] + strw/2, usr1[3] + strh/2, ann, cex= cex )

dev.copy2pdf( file= file )
}



This produces a little line in the lower left corner of the figure, containing the working directory, file name and date, and then saves it to the given file name. Use it in place of dev.copy2pdf().