smoothPalette

Often I need to map a numeric vector on a palette, e.g. create a gradient in which the lowest value is blue, highest is red, and everything in between nicely spread. I found this function useful.

smoothPalette <- function( x, max= NULL, min= NULL, palfunc= NULL, n= 10, symmetrical= FALSE ) {

  require( RColorBrewer )
  if( missing( palfunc ) ) {
    palfunc <- colorRampPalette( c( "blue", "white", "red" ) )
  }

  pal <- palfunc( n )
  nas <- which( is.na( x ) )

  x[ nas ] <- mean( x, na.rm= T )

  if( missing( max ) ) max <- max( x )
  x[ x >= max ] <- max

  if( missing( min ) ) min <- min( x )
  x[ x <= min ] <- min

  if( symmetrical ) {
    mm <- max( abs( c( min, max ) ) )
    max <- mm
    min <- -mm
  }


  ret <- findInterval( x, seq( min, max, length.out= n + 1 ), rightmost.closed= T )
  ret <- pal[ ret ]
  ret[ nas ] <- "white"
  return( ret )
}

Usage is simple:

> a <- sort( rnorm( 1000 ) )
> plot( 1:length( a ), a, col= smoothPalette( a, n= 100 ), pch= 19, cex= 2 )

The result:

test

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().