[R] colorRamp of image to span larger range than dataset

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Mon Sep 6 10:18:22 CEST 2010


On Mon, Sep 6, 2010 at 2:21 AM,  <Bill.Venables at csiro.au> wrote:
> colorRampPalette returns a function, not a list of colours.  You might want to try something like:
>
> ascols <-
>    colorRampPalette(c("gray", "yellow", "darkgoldenrod1", "orange", "red"), interpolate="spline")
> x <- 10*(1:nrow(volcano))
> y <- 10*(1:ncol(volcano))
> image(x, y, volcano, col = ascols(300), axes = FALSE)
>
> ### spot the difference...

 That doesn't work - all it does is use a palette of 300 colours to
span the range of the data. At least the plot will actually show
something now rather than failing, but its not what the poster wanted.

 I wrote a package to handle this kind of thing, called
"colourschemes" - not yet on CRAN, get from R-forge:

install.packages("colourschemes", repos="http://R-Forge.R-project.org")

the package lets you define colour scheme functions that map values to
colours. By using the same function to set colours for different plots
you can ensure a consistent mapping of value to colour, even for data
with wildly varying data ranges.

The examples in the vignette show how to use them with image() which
is a bit tricky since image() can only plot against a palette and not
individual colours.

 Here's how you'd create the palette using colourschemes:

 > rs = rampInterpolate(c(0,300),c("gray","yellow","darkgoldenrod1","orange","red"))

 'rs' is now a colour scheme function. Try rs(0), rs(195) or rs(300).
You get back the colours that correspond to those values. Now to see
the whole palette try:

 > plot(0:300,col=rs(0:300))

 (assuming you want the colour scheme to start at 0). See the vignette
for more examples.

 Of course if you are dealing with lots of raster data then you
probably want the raster package anyway, which is something else
entirely...

Barry



More information about the R-help mailing list