在Plotly中将回归平面添加到3d散点图中 [英] Add Regression Plane to 3d Scatter Plot in Plotly

查看:187
本文介绍了在Plotly中将回归平面添加到3d散点图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望利用Plotly中的出色功能,但是很难弄清楚如何向3d散点图添加回归平面.这是一个如何开始使用3d图的示例,有人知道如何进行下一步并添加平面吗?

I am looking to take advantage of the awesome features in Plotly but I am having a hard time figuring out how to add a regression plane to a 3d scatter plot. Here is an example of how to get started with the 3d plot, does anyone know how to take it the next step and add the plane?

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调用创建的预测对象对点进行采样.这将创建类似于火山对象的表面,然后可以将其添加到绘图中

You need to sample the points based on the predict object created from your lm call. This creates a surface similar to the volcano object which you can then add to your plot.

library(plotly)
library(reshape2)

#load data

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

以下内容设置了我们的表面范围.我选择每0.05点取样一次,并使用数据集的范围作为极限.可以在这里轻松修改.

The following sets up the extent of our surface. I chose to sample every 0.05 points, and use the extent of the data set as my limits. Can easily be modified here.

#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值.现在我们只需要创建基础图(点),为每种物种添加颜色和文本:

At this point, we have petal_lm_surface, which has the z value for every x and y we want to graph. Now we just need to create the base graph (the points), adding color and text for each species:

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

这篇关于在Plotly中将回归平面添加到3d散点图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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