r3dplotlyscatter-plotplane

Adding a Custom Plane to a 3-Dimensional 'plotly' Plot in R


Using the plotly package, I have the following plot.

library (plotly)
Data_Frame <- iris
Plot_1 <- plotly::plot_ly(Data_Frame, x = ~Sepal.Length, y = ~Petal.Length, z = ~Petal.Width)
Plot_1

I'd like to add the following surface to it.

x_Values <- c(min(Data_Frame$Sepal.Length), max(Data_Frame$Sepal.Length))
y_Values <- c(min(Data_Frame$Petal.Length), max(Data_Frame$Petal.Length))
Points_in_the_Plane <- expand.grid(x_Values, y_Values)
colnames(Points_in_the_Plane) <- c('x', 'y')
Points_in_the_Plane$z <- rep(0, nrow(Points_in_the_Plane))
Plot_2 <- plotly::plot_ly(x = ~x, y = ~y, z = ~z, type = 'mesh3d', opacity = 0.5, data = Points_in_the_Plane)
Plot_2

I'm having trouble combining these since they use different data frames as starting points. Is there a solution?


Solution

  • I figured it out!

    Number_of_Observations <- 100
    Data_Frame <- data.frame(x = rnorm(Number_of_Observations), y = rnorm(Number_of_Observations), z = rnorm(Number_of_Observations))
    x_Values <- c(min(Data_Frame$x), max(Data_Frame$x))
    y_Values <- c(min(Data_Frame$y), max(Data_Frame$y))
    Points_in_the_Plane <- expand.grid(x_Values, y_Values)
    colnames(Points_in_the_Plane) <- c('x', 'y')
    Points_in_the_Plane$z <- rep(0, nrow(Points_in_the_Plane))
    plotly::plot_ly(Points_in_the_Plane, x = ~x, y = ~y, z = ~z, type = 'mesh3d', opacity = 0.5) %>%
      plotly::add_trace(data = Data_Frame, x = ~x, y = ~y, z = ~z, type = 'scatter3d', opacity = 1)