Using scatterplot3d
in R, I'm trying to draw red lines from the observations to the regression plane:
wh <- iris$Species != "setosa"
x <- iris$Sepal.Width[wh]
y <- iris$Sepal.Length[wh]
z <- iris$Petal.Width[wh]
df <- data.frame(x, y, z)
LM <- lm(y ~ x + z, df)
library(scatterplot3d)
G <- scatterplot3d(x, z, y, highlight.3d = FALSE, type = "p")
G$plane3d(LM, draw_polygon = TRUE, draw_lines = FALSE)
To obtain the 3D equivalent of the following picture:
In 2D, I could just use segments
:
pred <- predict(model)
segments(x, y, x, pred, col = 2)
But in 3D I got confused with the coordinates.
Using the dataset from here, you can do
And another interactive version using
rgl
packageYou could use the scatter3d() function of the Rcmdr package.
I decided to include my own implementation as well, in case anyone else wants to use it.
The Regression Plane
The Residuals
The End Result:
While I really appreciate the convenience of the
scatterplot3d
function, in the end I ended up copying the entire function from github, since several arguments that are in baseplot
are either forced by or not properly passed toscatterplot3d
(e.g. axis rotation withlas
, character expansion withcex
,cex.main
, etc.). I am not sure whether such a long and messy chunk of code would be appropriate here, so I included the MWE above.Anyway, this is what I ended up including in my book:
(Yes, that is actually just the iris data set, don't tell anyone.)