Jos*_*osh 10 regression r plotly scatter3d r-plotly
我希望利用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)
Run Code Online (Sandbox Code Playgroud)
Chr*_*ris 14
您需要根据通过lm呼叫创建的预测对象对点进行采样.这会创建一个类似于火山物体的表面,然后您可以将其添加到您的绘图中.
library(plotly)
library(reshape2)
#load data
my_df <- iris
petal_lm <- lm(Petal.Length ~ 0 + Sepal.Length + Sepal.Width,data = my_df)
Run Code Online (Sandbox Code Playgroud)
以下列出了我们的表面范围.我选择每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
Run Code Online (Sandbox Code Playgroud)
在这一点上,我们有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))
Run Code Online (Sandbox Code Playgroud)
然后添加表面:
iris_plot <- add_trace(p = iris_plot,
z = petal_lm_surface,
x = axis_x,
y = axis_y,
type = "surface")
iris_plot
Run Code Online (Sandbox Code Playgroud)