Making plots using model objects you have created outside of ggplot2

This uses a function called predictvals.

The function extracts the x range of the data – the exact way this is done depends on the type of model object. The method here works with lm and glm objects (I think), but you need something different for loess objects, for example. I haven't tested other model objects with this clde

# 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(model, xvar, yvar, xrange=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
  if (is.null(xrange)) {
    if (any(class(model) %in% c("lm", "glm")))
      xrange <- range(model$model[[xvar]])
    else if (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
}

Demonstration

With linear model

# Create a linear model and make a prediction data frame
mod_lm <- lm(mpg ~ wt, data = mtcars)
predicted_lm <- predictvals(mod_lm, xvar = "wt", yvar = "mpg")

# Plot it
library(ggplot2)
p <- ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point()
p + geom_line(data=predicted_lm, colour="blue")

plot of chunk unnamed-chunk-2

With linear models of subgroups

It's also possible to use dlply and ldply from plyr to make predictions on multiple subgroups. Here we'll group by cyl and use facets.

# Predictions, splitting on grouping vars
library(plyr)

# Using lm, predict mpg from wt, and split on cyl
# Using dlply will create a list of lm objects for each subset
models_lm <- dlply(mtcars, "cyl", lm, formula = mpg ~ wt)

# Now we use ldply to create a prediction data frame that uses each model
predicted_lm_cyl <- ldply(models_lm, predictvals, xvar = "wt", yvar = "mpg")

# Finally, make a plot
p + geom_line(data=predicted_lm_cyl, colour="blue") + facet_wrap(~cyl)

plot of chunk unnamed-chunk-3