Graphics Reference
In-Depth Information
# Function to interleave the elements of two vectors
interleave
<-
function
function
(v1, v2) as.vector(rbind(v1,v2))
With these utility functions defined, we can make a linear model from the data and plot it as a
library(rgl)
# Make a copy of the data set
m
<-
mtcars
# Generate a linear model
mod
<-
lm(mpg ~ wt
+
disp
+
wt:disp, data
=
m)
# Get predicted values of mpg from wt and disp
m$pred_mpg
<-
predict(mod)
# Get predicted mpg from a grid of wt and disp
mpgrid_df
<-
predictgrid(mod,
"wt"
,
"disp"
,
"mpg"
)
mpgrid_list
<-
df2mat(mpgrid_df)
# Make the plot with the data points
plot3d(m$wt, m$disp, m$mpg, type
=
"s"
, size
=
0.5
, lit
=
FALSE
FALSE
)
# Add the corresponding predicted points (smaller)
spheres3d(m$wt, m$disp, m$pred_mpg, alpha
=
0.4
, type
=
"s"
, size
=
0.5
, lit
=
FALSE
FALSE
)
# Add line segments showing the error
segments3d(interleave(m$wt, m$wt),
interleave(m$disp, m$disp),
interleave(m$mpg, m$pred_mpg),
alpha
=
0.4
, col
=
"red"
)
# Add the mesh of predicted values
surface3d(mpgrid_list$wt, mpgrid_list$disp, mpgrid_list$mpg,
alpha
=
0.4
, front
=
"lines"
, back
=
"lines"
)