How do I add surfaces such a planes as traces generated mathematical formulas in a 3D scatter plot in plotly in r?

我只是一个虾纸丫 提交于 2019-12-11 10:46:48

问题


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

回答1:


Add inherit=FALSE inside add_trace:

p <- plot_ly(df, x = ~x, y = ~y, z = ~z, color = ~col, colors=c('#BF382A', '#0C4B8E')) %>%
  add_markers() %>%
  add_trace(z=surface2, x=axis_x, y=axis_y, type="surface", inherit=FALSE) %>%
  layout(scene = list(xaxis = list(title = 'X'), yaxis = list(title = 'Y'),
                     zaxis = list(title = 'Z'), aspectmode='cube')) 
print(p)



来源:https://stackoverflow.com/questions/46326005/how-do-i-add-surfaces-such-a-planes-as-traces-generated-mathematical-formulas-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!