# R/Perspective Plots

Jump to: navigation, search

How can you make a plot like this one in R? asks an esteemed friend of the QERM cause.

Sadly, in spite of his early bluster, Ian quickly discovered that "add" is not an option in the persp function. Indeed, this is a complex issue because the different surfaces need to be drawn on top of each other, but the one that's "on top" depends on the position in the x and y plane.

Here's a related discussion, but they're not dealing with transparency (which maybe wasn't available in R in 2002): http://tolstoy.newcastle.edu.au/R/help/02a/2046.html

# Ian's suggestion The code here is a first attempt to deal with this, and resulted in the plot below.

Clearly there are problems. The biggest one is that the attempt to subset the plots based on their relative order only occurs at the grid points. Since the place that they cross does not necessarily occur at a grid point, then this leaves those silly looking gaps. One solution would be to define a grid that somehow included all the lines on which there are overlaps, but for diagonal overlaps that would be impossible.

Hmmm... this is one to set aside and come back to later, I think.

-Ian 13:06, 19 February 2009 (PST)

# Eli's suggestion

My solution, on the right, is not so elegant. In fact, with a four-layered loop, it defies the limits of unelegantness. But it appears to have solved some of Ian's problems.

There is no "add" in persp, but you can use the standard "lines", "points" and "polygons" functions (which are effective "add"s) with the help of "trans3d", which converts the x, y and z coordinates to two dimensional coordinates given a persp plot.

The code is here: R/Perspective Plots/Code2

## caveat

Lest anybody think that the solution is remotely robust or widely applicable, let me present what happens when we replace Ian's well-behaved planes with:

```x <- seq(-10, 10, length= 30)
y <- x
f1 <- function(x,y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r }
z1 <- outer(x, y, f1)
z2 <- -1*outer(x,y, f1)
z3 <- 0*outer(x,y, f1)
```