Graphics Reference
In-Depth Information
sp + geom_line(data = predicted, size = 1 )
Discussion
Any model object can be used, so long as it has a corresponding predict() method. For ex-
ample, lm has predict.lm() , loess has predict.loess() , and so on.
Adding lines from a model can be simplified by using the function predictvals() , defined
next. If you simply pass in a model, it will do the work of finding the variable names and range of
the predictor, and will return a data frame with predictor and predicted values. That data frame
can then be passed to geom_line() to draw the fitted line, as we did earlier:
# Given a model, predict values of yvar from xvar
# This supports one predictor and one predicted variable
# xrange: If NULL, determine the x range from the model object. If a vector with
# two numbers, use those as the min and max of the prediction range.
# samples: Number of samples across the x range.
# ...: Further arguments to be passed to predict()
predictvals <- function
function (model, xvar, yvar, xrange = NULL
NULL , samples = 100 , ... ) {
# If xrange isn't passed in, determine xrange from the models.
# Different ways of extracting the x range, depending on model type
iif (is.null(xrange)) {
iif (any(class(model) %in% c( "lm" , "glm" )))
xrange <- range(model$model[[xvar]])
else
else iif (any(class(model) %in% "loess" ))
xrange <- range(model$x)
}
newdata <- data.frame(x = seq(xrange[ 1 ], xrange[ 2 ], length.out = samples))
names(newdata) <- xvar
newdata[[yvar]] <- predict(model, newdata = newdata, ... )
newdata
}
With the heightweight data set, we'll make a linear model with lm() and a LOESS model
with loess() ( Figure 5-22 ):
modlinear <- lm(heightIn ~ ageYear, heightweight)
modloess <- loess(heightIn ~ ageYear, heightweight)
Then we can call predictvals() on each model, and pass the resulting data frames to
geom_line() :
Search WWH ::




Custom Search