Add in Plane using Plotly in R

350 views Asked by At

I am new to using plotly, and I am trying to add a set of planes into data at specific points.

I have been able to add the planes in scatterplot3d successfully with the following code:

my_data <- mtcars

# Create Scatter Plot 
library(scatterplot3d)
# Scale data accordingly 
cars_3d_plot <- scatterplot3d(x = scale(my_data$drat), y = scale(my_data$wt), z = scale(my_data$qsec), 
                            highlight.3d = F, type = "p", 
                            pch = 16,  
                            ylab = "wt (y)", zlab = "qsec (z)", xlab = "drat (x)",
                            xlim = c(-4,5), 
                            ylim = c(-4,5), 
                            zlim = c(-4,5))

# Put in Qsec Cut - scale down from 20
qsec_cut <- (20-mean(my_data$qsec, na.rm = T))/sd(my_data$qsec, na.rm = T)

cars_3d_plot$plane3d(qsec_cut, 0, 0)


# Put in Drat Cut at 3.596563
drat_before <- 3.596563

drat_scaled <- (3.596563 - mean(my_data$drat, na.rm = T))/sd(my_data$drat, na.rm = T)

# YZ
# THIS CUTS THE PLANE AT X = 5
x0 <- drat_scaled
xyz1 <- cars_3d_plot$xyz.convert(rep(x0, 11), rep(-4, 11), seq(-4, 6, by=1))
xyz2 <- cars_3d_plot$xyz.convert(rep(x0, 11), rep(6, 11), seq(-4, 6, by=1))
segments(xyz1$x, xyz1$y, xyz2$x, xyz2$y, lty="dotted")

xyz1 <- cars_3d_plot$xyz.convert(rep(x0, 11), seq(-4, 6, by=1), rep(-4, 11))
xyz2 <- cars_3d_plot$xyz.convert(rep(x0, 11), seq(-4, 6, by=1), rep(6, 11))
segments(xyz1$x, xyz1$y, xyz2$x, xyz2$y, lty="dotted")

However, I would like to make it interactive and use plotly.

I have read this page (Add Regression Plane to 3d Scatter Plot in Plotly) and have successfully added a regression (can give code if needed)

However, I would really like to add these planes in an interactive form in plotly and am quite stuck :(. If you could please help or point in the right direction :) Thank you in advance.

I have tried using the rgl package but with the data I have it doesn't compute the axis properly and I have gone down the plotly rabbit hole.

Edit: I have used add_mesh to add on the z-axis, however, how do I add a mesh for when x = 4?

my_data <- mtcars

df <- data.frame(x = my_data$drat, y = my_data$wt, z = my_data$qsec)
planDf <- data.frame(x = rep(range(df$x, na.rm = T), 2), y = rep(range(df$y, na.rm = T), each = 2), z = 20)
plan_df_2 <- data.frame(x = rep(range(df$x, na.rm = T), 2), y = rep(range(df$y, na.rm = T), each = 2), z = 100)
library(plotly)
my_data$gear = as.character(my_data$gear)

plot_ly(my_data) %>%
  add_markers(x = ~drat, y = ~wt, z = ~qsec, color = ~gear, colors = c("firebrick", "forestgreen", "orange")) %>%
  add_mesh(x = ~x, y = ~y, z = ~z, data = planDf, opacity = 0.3)
0

There are 0 answers