Graphics Reference
In-Depth Information
Adding a Prediction Surface to a Three-Dimensional
Plot
Problem
You want to add a surface of predicted value to a three-dimensional scatter plot.
Solution
First we need to define some utility functions for generating the predicted values from a model
object:
# Given a model, predict zvar from xvar and yvar
# Defaults to range of x and y variables, and a 16x16 grid
predictgrid
<-
function
NULL
) {
# Find the range of the predictor variable. This works for lm and glm
# and some others, but may require customization for others.
xrange
<-
range(model$model[[xvar]])
yrange
<-
range(model$model[[yvar]])
function
(model, xvar, yvar, zvar, res
=
16
, type
=
NULL
newdata
<-
expand.grid(x
=
seq(xrange[
1
], xrange[
2
], length.out
=
res),
y
=
seq(yrange[
1
], yrange[
2
], length.out
=
res))
names(newdata)
<-
c(xvar, yvar)
newdata[[zvar]]
<-
predict(model, newdata
=
newdata, type
=
type)
newdata
}
# Convert long-style data frame with x, y, and z vars into a list
# with x and y as row/column values, and z as a matrix.
df2mat
<-
function
function
(p, xvar
=
NULL
NULL
, yvar
=
NULL
NULL
, zvar
=
NULL
NULL
) {
iif
(is.null(xvar)) xvar
<-
names(p)[
1
]
iif
(is.null(yvar)) yvar
<-
names(p)[
2
]
iif
(is.null(zvar)) zvar
<-
names(p)[
3
]
x
<-
unique(p[[xvar]])
y
<-
unique(p[[yvar]])
z
<-
matrix(p[[zvar]], nrow
=
length(y), ncol
=
length(x))
m
<-
list(x, y, z)
names(m)
<-
c(xvar, yvar, zvar)
m
}