I'm trying to learn how to draw surfaces in a 3D scatter plot in Plotly using R.
I tried to extend the example give in this questions: Add Regression Plane to 3d Scatter Plot in Plotly
Except I changed the example from using a standard Iris data set to using to random clusters separated by a 2D plane with the formula: Z = -X -Y
I get the error:
Error in traces[[i]][[obj]] :
attempt to select less than one element in get1index
So I set up my data to be divided by the plane
rm(list=ls())
library(plotly)
library(reshape2)
x <- rnorm(100,1,1)
y <- rnorm(100,1,1)
z <- rnorm(100,1,1)
col <- rep("red",100)
df.1 <- data.frame(x,y,z,col)
x <- rnorm(100,-1,1)
y <- rnorm(100,-1,1)
z <- rnorm(100,-1,1)
col <- rep("blue",100)
df.2 <- data.frame(x,y,z,col)
df<- rbind(df.1,df.2)
Next, I want to calculate a surface for a plane whose formula is x + y + z = 0
graph_reso <- 0.1
#Setup Axis
axis_x <- seq(min(df$x), max(df$x), by = graph_reso)
axis_y <- seq(min(df$x), max(df$x), by = graph_reso)
surface <- expand.grid(x = axis_x,y = axis_y,KEEP.OUT.ATTRS = F)
Here I compute the surface - in the cited example they use linear regression
surface$z <- 0 - surface$x - surface$y
surface2 <- acast(surface, y ~ x, value.var = "z") #y ~ x
Next, I use plot_ly to create the 3D scatter plot -- which works fine
p <- plot_ly(df, x = ~x, y = ~y, z = ~z, color = ~col, colors = c('#BF382A', '#0C4B8E')) %>%
add_markers() %>%
layout(scene = list(xaxis = list(title = 'X'),
yaxis = list(title = 'Y'),
zaxis = list(title = 'Z')))
So this is the step where I get stuck -- I guess I'm not creating my surface correctly. Tried google and troubleshooting -- it seems I'm stuck.
add_trace(p,z=surface2,x=axis_x,y=axis_y,type="surface")
The error I get is:
Error in traces[[i]][[obj]] :
attempt to select less than one element in get1index
Add
inherit=FALSE
insideadd_trace
: