Search code examples
rplotly

Plot 3d plane from x+y+z=6 equation in plotly


I have a set of equations (z1) x+y+z=6, (z2) x+2y+2z=9 and (z3) x+3y+4z=13 and would like to plot the planes using plotly.

Method1: using mesh3d

require(plotly)

x<-seq(from=-10, to=10, by=1)
y<-seq(from=-10, to=10, by=1)
z1<-6-x-y #For the first plane

fig <- plot_ly(x = ~, y = ~y, z = ~z1, type = 'mesh3d')
fig

Produces no output though. Why?

Method 2: Using surface

Whereas this produces a plane but the wrong one.

library(plotly)

x<-seq(from=-10,to=10,by=1)
y<-seq(from=-10,to=10,by=1)

z1<-6-x-y
z1<-matrix(rep(z1,10),NROW(x),10)

fig <- plot_ly(showscale = FALSE)
fig <- fig %>% add_surface(z = ~z1)
fig

This plane is not correct. If you look at the point x=2, y=2, z should equal 2 but it doesn't. Instead it is 22, and that's not correct.

enter image description here


Solution

  • When x <- seq(from=-10, to=10, by=1); y<-seq(from=-10, to=10, by=1), x+y+z=6 is not plane but line.
    You need to prepare more data points.

    library(dplyr); library(tidyr); library(plotly)
    
    x <- seq(from=-10, to=10, by=1)
    y <- seq(from=-10, to=10, by=1)
    z1 <- 6-x-y #For the first plane
    
    origin <- tibble(x = x, y = y, z = z1)
    # prepare all combination of x and y, and calculate z1
    xyz1 <- tidyr::crossing(x, y) %>%
      mutate(z1 = 6-x-y)
    
    plot_ly(x = ~x, y = ~y, z = ~z1, type = "mesh3d", data = xyz1) %>% 
      add_markers(~ x, ~y, ~z1, data = origin)
    

    Orange points are the data you prepare (when x <- seq(from=-10, to=10, by=1); y<-seq(from=-10, to=10, by=1) , x+y+z=6 is line.) enter image description here