我正在尝试学习如何使用R在Plotly中绘制三维散点图中的曲面。
我尝试在这些问题中扩展示例:Add Regression Plane to 3d Scatter Plot in Plotly
除了我将使用标准Iris数据集的示例更改为使用由2D平面分隔的随机簇,其公式为:Z = -X -Y
我收到错误:
Error in traces[[i]][[obj]] :
attempt to select less than one element in get1index
所以我将数据设置为由平面划分
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)
接下来,我想计算公式为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)
这里我计算表面 - 在引用的例子中,他们使用线性回归
surface$z <- 0 - surface$x - surface$y
surface2 <- acast(surface, y ~ x, value.var = "z") #y ~ x
接下来,我使用plot_ly创建3D散点图 - 工作正常
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')))
所以这就是我陷入困境的一步 - 我猜我没有正确地创造我的表面。尝试谷歌和故障排除 - 似乎我被卡住了。
add_trace(p,z=surface2,x=axis_x,y=axis_y,type="surface")
我得到的错误是:
Error in traces[[i]][[obj]] :
attempt to select less than one element in get1index
答案 0 :(得分:2)
在inherit=FALSE
内添加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)