在 Plotly 中将回归平面添加到 3d 散点图

Add Regression Plane to 3d Scatter Plot in Plotly

我希望利用 Plotly 中的强大功能,但我很难弄清楚如何将回归平面添加到 3d 散点图。这是一个如何开始使用 3d 图的示例,有人知道下一步如何添加平面吗?

library(plotly)
data(iris)


iris_plot <- plot_ly(my_df, 
                x = Sepal.Length, 
                y = Sepal.Width, 
                z = Petal.Length, 
                type = "scatter3d", 
                mode = "markers")

petal_lm <- lm(Petal.Length ~ 0 + Sepal.Length + Sepal.Width, 
               data = iris)

您需要根据 lm 调用创建的预测对象对点进行采样。这将创建一个类似于 volcano 对象的表面,然后您可以将其添加到绘图中。

library(plotly)
library(reshape2)

#load data

my_df <- iris
petal_lm <- lm(Petal.Length ~ 0 + Sepal.Length + Sepal.Width,data = my_df)

下面设置我们表面的范围。我选择每 0.05 个点采样一次,并使用数据集的范围作为我的限制。可以在这里轻松修改。

#Graph Resolution (more important for more complex shapes)
graph_reso <- 0.05

#Setup Axis
axis_x <- seq(min(my_df$Sepal.Length), max(my_df$Sepal.Length), by = graph_reso)
axis_y <- seq(min(my_df$Sepal.Width), max(my_df$Sepal.Width), by = graph_reso)

#Sample points
petal_lm_surface <- expand.grid(Sepal.Length = axis_x,Sepal.Width = axis_y,KEEP.OUT.ATTRS = F)
petal_lm_surface$Petal.Length <- predict.lm(petal_lm, newdata = petal_lm_surface)
petal_lm_surface <- acast(petal_lm_surface, Sepal.Width ~ Sepal.Length, value.var = "Petal.Length") #y ~ x

此时,我们有 petal_lm_surface,它具有我们想要绘制的每个 x 和 y 的 z 值。现在我们只需要创建基础图(点),为每个物种添加颜色和文本:

hcolors=c("red","blue","green")[my_df$Species]
iris_plot <- plot_ly(my_df, 
                     x = ~Sepal.Length, 
                     y = ~Sepal.Width, 
                     z = ~Petal.Length,
                     text = ~Species, # EDIT: ~ added
                     type = "scatter3d", 
                     mode = "markers",
                     marker = list(color = hcolors))

然后添加曲面:

iris_plot <- add_trace(p = iris_plot,
                       z = petal_lm_surface,
                       x = axis_x,
                       y = axis_y,
                       type = "surface")

iris_plot

我执行了代码,但出现错误,我在 text = "Species" 时更正了它,是的,它正确执行了

用这个替换代码的绘图部分,也修复了错误:

attach(my_df)
iris_plot <- plot_ly(my_df, 
                     x = ~Sepal.Length, 
                     y = ~Sepal.Width, 
                     z = ~Petal.Length,
                     text = Species, 
                     type = "scatter3d",
                     color = ~Species,
                     colors = c("red","blue","green"),
                     mode = "markers")

我使用了相同的代码,但是当我运行获取表面的最后一步时收到此错误消息:

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

所以我在 "add_trace" 中添加了一项:

inherit = F

最后。