Fadi - 8 months ago 27

R Question

I'm really new to R and I want to create an Image like the one I added here, but I need to have the Color Range from 0 to 1, right now it's set automatically, in the image it is from 0.2 to 0.6.

Here is my R code that I use:

Mat.csv is a 2D Matrix with values in [0,1]

`library(plot3D)`

mydata <- read.csv("D:/output/Mat.csv")

mydata <- as.matrix(mydata)

pdf("D:/output/surfaceplot.pdf")

mycols <- colorRampPalette( c("#ff0000", "#00ff00") )

persp3D(z = mydata, theta = 120, zlim=c(0,1))

dev.off()

Example Graph

Answer

Argument `clim`

will solve your problem. (`persp3D`

is a `plot3D`

package's function, but `persp3d`

is a `rgl`

package's function. Be careful.) `colorRampPalette`

returns `function`

that interpolate a set of given colors to create new function's argument number of colors. So you can set persp3D's color vector by giving the output of new `function`

that `colorRampPalette`

returns. For example, `persp3D(..., col = mycols(256))`

or, `mycolv <- mycols(256); persp3D(..., col = mycolv)`

```
library(plot3D)
## example data
x <- seq(-pi, pi, by = 0.1)
y <- seq(-pi, pi, by = 0.1)
mydata <- outer(x, y, function(x, y) cos(x) * sin(y))
range(mydata) # about -1 ~ 1
## colour function
mycols <- colorRampPalette(c("blue", "red", "green", "yellow"))
## draw
persp3D(z = mydata, ticktype = "detailed", col = mycols(256)) # left
persp3D(z = mydata, ticktype = "detailed", col = mycols(256), clim=c(-2, 2)) # right
```