When did this magic happen, and is there any documentation about how to work with it? Is it just converting the lm object to a data.frame with broom::augment()?
My students make residual plots of everything, so an easy way of doing this with ggplot2 would be great.
Yeah, I teach my students to use broom on the models and then make the plots with the resulting data.frame. But I've been trying to find some shortcuts because it gets old copying and modifying the 20 or so lines of code needed to replicate what plot.lm() does with 6 characters.
Yes, DRY, so I should make a function, and I have, but it's not working very well.
"From what I can see ..." -- where? is this done inside ggplot()? I looked for a ggplot.lm() method but ...
if you don't mind sharing the function we could take a look at it and see if we can make it better
I was a little brief in my last response so let me try to clarify a little deeper:
We can see the inner workings of ggplot() by typing ggplot2:::ggplot in the console (or pressing F2 with the cursor on the function) which gives us the following:
UseMethod("ggplot") is telling you that ggplot() is a (S3) generic function that has methods for different object classes. So we can list all the methods of ggplot() with the methods() function.
> methods(ggplot)
[1] ggplot.data.frame* ggplot.default*
see '?methods' for accessing help and source code
which tells us that there are currently two methods for the ggplot function. UseMethod will use the class of the input to figure out which method to use.
In our case was the output of an lm call which only have 1 class, namely "lm":
class(lm(Sepal.Length ~ Sepal.Width, data = iris))
[1] "lm"
ggplot.lm does not exist in the available methods as you correctly have noticed which leads UseMethod to fallback to look for a default method. That is, it looks for ggplot.default. Which it finds and calls. And if we look at the source code for ggplot.default we get the following