首页 文章

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

提问于
浏览
5

我希望利用Plotly中的强大功能,但我很难弄清楚如何将回归平面添加到三维散点图中 . 以下是如何开始使用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)

1 回答

  • 7

    您需要根据从 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, 
                         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
    

    enter image description here

相关问题