[R] Persp and color (again)

ucgamdo@ucl.ac.uk ucgamdo at ucl.ac.uk
Wed Sep 17 13:42:48 CEST 2003


Hi guys,

  After all the discussion yesterday about persp and color, I decided to
have a more closer look at demo(persp), and decided to write a function to
generate 'topo-like' colours to plot perspectives (Thanks a lot to Uwe
Ligges for his enlightning comments regarding the code in the demo).

Here it goes, I believe that this function will be pretty useful to a lot
of people:

###########################################################################
# Function to generate a matrix of colors to be used in perspective plots
# (based on demo(persp) and the comments of U. Ligges
###########################################################################

surf.colors <- function(x, col = terrain.colors(20)) {

  # First we drop the 'borders' and average the facet corners
  # we need (nx - 1)(ny - 1) facet colours!
  x.avg <- (x[-1, -1] + x[-1, -(ncol(x) - 1)] +
             x[-(nrow(x) -1), -1] + x[-(nrow(x) -1), -(ncol(x) - 1)]) / 4

  # Now we construct the actual colours matrix
  colors = col[cut(x.avg, breaks = length(col), include.lowest = T)]

  return(colors)
}

# Now lets look at an example of using it:

# first lets build some random surface
library(MASS)
x <- cbind(rnorm(100), rnorm(100))
x <- kde2d(x[,1], x[,2], n = 100)$z

# now lets plot it!
par(bg = "gray")

persp(x, col = surf.colors(x), phi = 30, theta = 225, box = F, border = NA,
shade = .4)

persp(x, col = surf.colors(x, col = heat.colors(40)), phi = 30, theta =
225, box = F, border = NA, shade = .4)

persp(x, col = surf.colors(x, col = topo.colors(40)), phi = 30, theta =
225, box = F, border = NA, shade = .4)

persp(x, col = surf.colors(x, col = gray(seq(0, 1, len = 40))), phi = 30,
theta = 225, box = F, border = NA, shade = .4)

# etc, etc, etc. I hope this will give you plenty of ideas, perhaps, the
writer of persp would like to
# add this as a subroutine so it can be called directly from within the
persp function, say
# persp(x, col = heat.colors(20), topo = TRUE, ...)




More information about the R-help mailing list