title: How do I add surfaces such a planes as traces generated mathematical formulas in a 3D scatter plot in plotly in r?
body: <p>I'm trying to learn how to draw surfaces in a 3D scatter plot in Plotly using R.</p>
  
  <p>I tried to extend the example give in this questions: <a href="https://stackoverflow.com/questions/38331198/add-regression-plane-to-3d-scatter-plot-in-plotly">Add Regression Plane to 3d Scatter Plot in Plotly</a></p>
  
  <p>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</p>
  
  <p>I get the error:</p>
  
  <pre><code>Error in traces[[i]][[obj]] : 
    attempt to select less than one element in get1index
  </code></pre>
  
  <p>So I set up my data to be divided by the plane</p>
  
  <pre><code>rm(list=ls())
  library(plotly)
  library(reshape2)
  x &lt;- rnorm(100,1,1)
  y &lt;- rnorm(100,1,1)
  z &lt;- rnorm(100,1,1)
  col &lt;- rep("red",100)
  df.1 &lt;- data.frame(x,y,z,col)
  x &lt;- rnorm(100,-1,1)
  y &lt;- rnorm(100,-1,1)
  z &lt;- rnorm(100,-1,1)
  col &lt;- rep("blue",100)
  df.2 &lt;- data.frame(x,y,z,col)
  df&lt;- rbind(df.1,df.2)
  </code></pre>
  
  <p>Next, I want to calculate a surface for a plane whose formula is x + y + z = 0</p>
  
  <pre><code>graph_reso &lt;- 0.1
  #Setup Axis
  axis_x &lt;- seq(min(df$x), max(df$x), by = graph_reso)
  axis_y &lt;- seq(min(df$x), max(df$x), by = graph_reso)
  surface &lt;- expand.grid(x = axis_x,y = axis_y,KEEP.OUT.ATTRS = F)
  </code></pre>
  
  <p>Here I compute the surface - in the cited example they use linear regression</p>
  
  <pre><code>surface$z &lt;- 0 - surface$x - surface$y
  surface2 &lt;- acast(surface, y ~ x, value.var = "z") #y ~ x
  </code></pre>
  
  <p>Next, I use plot_ly to create the 3D scatter plot -- which works fine</p>
  
  <pre><code>p &lt;- plot_ly(df, x = ~x, y = ~y, z = ~z, color = ~col, colors = c('#BF382A', '#0C4B8E')) %&gt;%
    add_markers() %&gt;%
    layout(scene = list(xaxis = list(title = 'X'),
                       yaxis = list(title = 'Y'),
                       zaxis = list(title = 'Z'))) 
  </code></pre>
  
  <p>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. </p>
  
  <pre><code>add_trace(p,z=surface2,x=axis_x,y=axis_y,type="surface")
  </code></pre>
  
  <p>The error I get is: </p>
  
  <pre><code>Error in traces[[i]][[obj]] : 
    attempt to select less than one element in get1index
  </code></pre>