How to plot a plane from an equation in R

14k views Asked by At

I've been tinkering with the RGL package to figure out how to plot a plane from an equation in R, to no avail.

For example, I would like to visualize the following plane:

1x + 0y + 0z = 2
0x + 1y + 0z = 3
0x + 0y + 1z = 4

It seems the rgl's planes3d function only adds a plane to an existing 3D plot.

2

There are 2 answers

1
RHertel On

If you want to plot, e.g., a plane defined by the equation 2*x+y-z-3=0, you could do this in the following way:

x <- y <- seq(-10, 10, length= 30)
f <- function(x,y){ z <- x*2 + y -3 }
z <- outer(x,y,f)
persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightblue")

For more examples see ?persp. This is the output

0
Lars Lau Raket On

Here is a simple example:

library(rgl)
# Create some dummy data
dat <- replicate(2, 1:3)

# Initialize the scene, no data plotted
plot3d(dat, type = 'n', xlim = c(-1, 1), ylim = c(-1, 1), zlim = c(-3, 3), xlab = '', ylab = '', zlab = '') 

# Add planes
planes3d(1, 1, 1, 0, col = 'red', alpha = 0.6)
planes3d(1, -1, 1, 0, col = 'orange', alpha = 0.6)
planes3d(1, -1, -1, -0.8, col = 'blue', alpha = 0.6)

Which gives the following result.

plane plot

As you can see, it is quite hard to understand the spatial structure from such a plot, but the interactivity of course helps. Alternatively you can plot the planes as wireframes, which will sometimes help in understanding the spatial structure:

# Evaluate planes
n <- 20
x <- y <- seq(-1, 1, length = n)
region <- expand.grid(x = x, y = y)

z1 <- matrix(-(region$x + region$y), n, n)
z2 <- matrix(-region$x + region$y, n, n)
z3 <- matrix(region$x - region$y - 0.8, n, n)

surface3d(x, y, z1, back = 'line', front = 'line', col = 'red', lwd = 1.5, alpha = 0.4)
surface3d(x, y, z2, back = 'line', front = 'line', col = 'orange', lwd = 1.5, alpha = 0.4)
surface3d(x, y, z3, back = 'line', front = 'line', col = 'blue', lwd = 1.5, alpha = 0.4)
axes3d()

wireframe planes