如何在r的3D散点图中添加诸如轨迹之类的平面以生成数学公式的轨迹? [英] How do I add surfaces such a planes as traces generated mathematical formulas in a 3D scatter plot in plotly in r?

查看:311
本文介绍了如何在r的3D散点图中添加诸如轨迹之类的平面以生成数学公式的轨迹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何使用R在Plotly中的3D散点图中绘制表面.

I'm trying to learn how to draw surfaces in a 3D scatter plot in Plotly using R.

我试图扩展给出以下问题的示例:将回归平面添加到Plotly中的3d散点图中

I tried to extend the example give in this questions: Add Regression Plane to 3d Scatter Plot in Plotly

除了我将示例从使用标准Iris数据集更改为使用改为由2D平面分隔的具有以下公式的随机聚类:Z = -X -Y

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

我得到了错误:

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)

接下来,我要为公式为x + y + z = 0的平面计算一个曲面

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

接下来,我使用plot_ly创建3D散点图-效果很好

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")

我得到的错误是:

Error in traces[[i]][[obj]] : 
  attempt to select less than one element in get1index

推荐答案

add_trace内添加inherit=FALSE:

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)

这篇关于如何在r的3D散点图中添加诸如轨迹之类的平面以生成数学公式的轨迹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆