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)
I used the same code, but I got this error message when I run the last step to get the surface:
So I add one term in the "add_trace" as:
at the end.
I executed the code but I get an error, I corrected it when
text = "Species"
and yes it executed correctlyReplacing the plot part of the code with this, also fixes the error:
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.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.
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:and then add the surface: