What is the Source Code for plot(linear_model)?

Hi!

As you may know, we can generate diagnostic plots for linear models using plot(linear_model)

iris |> 
  lm(formula = Sepal.Length ~ Sepal.Width) |> 
  plot()

The output is like this:

image

It seems like there is no source code for this function and I wonder how the red line fits the data in image 1, 3 and 4.

Thank you in advance for your help!

plot is a generic function. A package that wants to use it defines its own version(s)
Below I show how the particular function is found.
First check the class of the object that you want to plot. In this case lm
Then see the documentation to find the package it belongs to. With ?lm I see that it is stats.
Then the function that is used will be called plot.lm in the package stats.
In most of these cases this will be an internal function of the package.
To see its definition type stats:::plot.lm (triple colon!)
For this message I deleted most of the output lines.
Good luck with studying the code!

whatobject <- iris |> 
  lm(formula = Sepal.Length ~ Sepal.Width) 
class(whatobject)
#> [1] "lm"
?lm
stats:::plot.lm 
#> function (x, which = c(1, 2, 3, 5), caption = list("Residuals vs Fitted", 
#>     "Normal Q-Q", "Scale-Location", "Cook's distance", "Residuals vs Leverage", 
#>     expression("Cook's dist vs Leverage* " * h[ii]/(1 - h[ii]))), 
#>     panel = if (add.smooth) function(x, y, ...) panel.smooth(x, 
#>         y, iter = iter.smooth, ...) else points, sub.caption = NULL, 
#>     main = "", ask = prod(par("mfcol")) < length(which) && dev.interactive(), 
#>     ..., id.n = 3, labels.id = names(residuals(x)), cex.id = 0.75, 
#>     qqline = TRUE, cook.levels = c(0.5, 1), cook.col = 8, cook.lty = 2, 
#>     cook.legendChanges = list(), add.smooth = getOption("add.smooth"), 
#>     iter.smooth = if (isGlm) 0 else 3, label.pos = c(4, 2), cex.caption = 1, 
#>     cex.oma.main = 1.25, extend.ylim.f = 0.08) 
.....  SOME (MOST) LINES LEFT OUT
#> {
#>     if (!one.fig && par("oma")[3L] >= 1) 
#>         mtext(sub.caption, outer = TRUE, cex = cex.oma.main)
#>     invisible()
#> }
#> <bytecode: 0x0000020081f38080>
#> <environment: namespace:stats>
Created on 2023-06-01 with reprex v2.0.2
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.