How to overlay a line for an lm object on a ggplot2 scatterplot

Earlier I asked a related question and Hadley had this good answer. Using the predict function from that post you can add two columns to your data. One for each model:

calvarbyruno.1$calQuad <- predict(calquad.1)
calvarbyruno.1$callin <- predict(callin.1)

Then it's a matter of plotting the point and adding each model in as a line:

ggplot() + 
geom_point(data=calvarbyruno.1, aes(PAR, Nominal), colour="green") + 
geom_line(data=calvarbyruno.1, aes(calQuad, Nominal), colour="red" ) + 
geom_line(data=calvarbyruno.1, aes(callin, Nominal), colour="blue" ) + 
opts(aspect.ratio = 1)

And that results in this nice picture (yeah the colors could use some work):

alt text
(source: cerebralmastication.com)


The easiest option is to use geom_smooth() and let ggplot2 fit the model for you.

ggplot(calvarbyruno.1, aes(y = PAR, x = Nominal, weight=Nominal^calweight)) + 
    geom_smooth(method = "lm") + 
    geom_smooth(method = "lm", formula = y ~ poly(x, 2), colour = "red") + 
    geom_point() + 
    coord_flip()

Illustration using geom_smooth

Or you can create a new dataset with the predicted values.

newdata <- data.frame(Nominal = pretty(calvarbyruno.1$Nominal, 100))
newdata$Linear <- predict(callin.1, newdata = newdata)
newdata$Quadratic <- predict(calquad.1, newdata = newdata)
require(reshape2)
newdata <- melt(newdata, id.vars = "Nominal", variable.name = "Model")
ggplot(calvarbyruno.1, aes(x = PAR, y = Nominal, weight=Nominal^calweight)) + 
    geom_line(data = newdata, aes(x = value, colour = Model)) + 
    geom_point()