Graphics Reference
In-Depth Information
Solution
Usually the easiest way to overlay a fitted model is to simply ask stat_smooth() to do it for
you, as described in Adding Fitted Regression Model Lines . Sometimes, however, you may want
to create the model yourself and then add it to your graph. This allows you to be sure that the
model you're using for other calculations is the same one that you see.
In this example, we'll build a quadratic model using lm() with ageYear as a predictor of
heightIn . Then we'll use the predict() function and find the predicted values of heightIn
across the range of values for the predictor, ageYear :
library(gcookbook) # For the data set
model <- lm(heightIn ~ ageYear + I(ageYear ^ 2 ), heightweight)
model
Call:
lm(formula = heightIn ~ ageYear + I(ageYear ^ 2 ), data = heightweight)
Coefficients:
(Intercept)
ageYear I(ageYear ^ 2 )
-10.3136
8.6673
-0.2478
# Create a data frame with ageYear column, interpolating across range
xmin <- min(heightweight$ageYear)
xmax <- max(heightweight$ageYear)
predicted <- data.frame(ageYear = seq(xmin, xmax, length.out = 100 ))
# Calculate predicted values of heightIn
predicted$heightIn <- predict(model, predicted)
predicted
ageYear heightIn
11.58000 56.82624
11.63980 57.00047
...
17.44020 65.47875
17.50000 65.47933
We can now plot the data points along with the values predicted from the model (as you'll see in
Figure 5-22 ) :
sp <- ggplot(heightweight, aes(x = ageYear, y = heightIn)) +
geom_point(colour = "grey40" )
Search WWH ::




Custom Search