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

Advertisements