# [R] 3D-surface colour based on the values of X or Y data points

Duncan Murdoch murdoch.duncan at gmail.com
Fri Nov 26 12:34:10 CET 2010

```On 26/11/2010 5:21 AM, suresh wrote:
>
> Dear R-experts,
>
> Using persp3d(), I plotted a 3d surface. I would like to colour this surface
> based on the result values (dependent variable) grouped in, say, three to
> five different ranges. Later, I would also like to paint the same surface
> based on the range-values of one of the independent variables.
>
> Thank you.
>
> Regards,
> Suresh
>

On 26/11/2010 5:21 AM, suresh wrote:
>
> Dear R-experts,
>
> Using persp3d(), I plotted a 3d surface. I would like to colour this
surface
> based on the result values (dependent variable) grouped in, say, three to
> five different ranges. Later, I would also like to paint the same surface
> based on the range-values of one of the independent variables.

You can specify a matrix of colours of the same shape as z.  It will be
used to specify the colour at each vertex of the mesh that is shown, and
colours will be interpolated between vertices.  Sharp edges are harder,
because it's ambiguous where the change should occur.  For those, you'll
need to plot surfaces one colour at a time, setting the z values for
other colours to NA so they aren't plotted.  The vertices at colour
boundaries will need to be plotted twice.

For example:

x <- y <- seq(-1,1,len=20)
z <- outer(x, y, function(x,y) x^2 + y^2)

# smooth changes first

colour <- ifelse(z < 1/2, "red", "white")
persp3d(x,y,z, col=colour)

# sharp edges next
open3d()
redvals <- ifelse(z < 1/2, z, NA)
surface3d(x, y, redvals, col="red")

# overplotting will not be shown since the x,y and z values are
# identical; only the empty areas will show as white
surface3d(x, y, z, col="white")

# now draw the box
decorate3d()

```