The Art of R Programming

(WallPaper) #1

12.1.2 Adding Lines: The abline() Function...............................


We now have an empty graph, ready for the next stage, which is adding
a line:



x <- c(1,2,3)
y <- c(1,3,8)
plot(x,y)
lmout <- lm(y ~ x)
abline(lmout)



After the call toplot(), the graph will simply show the three points, along
with thex- andy- axes with hash marks. The call toabline()then adds a line
to the current graph. Now, which line is this?
As you learned in Section 1.5, the result of the call to the linear-regression
functionlm()is a class instance containing the slope and intercept of the fit-
ted line, as well as various other quantities that don’t concern us here. We’ve
assigned that class instance tolmout. The slope and intercept will now be in
lmout$coefficients.
So, what happens when we callabline()? This function simply draws
a straight line, with the function’s arguments treated as the intercept and
slope of the line. For instance, the callabline(c(2,1))draws this line on what-
ever graph you’ve built up so far:


y=2+1·x
Butabline()is written to take special action if it is called on a regression
object (though, surprisingly, it is not a generic function). Thus, it will pick
up the slope and intercept it needs fromlmout$coefficientsand plot that
line. It superimposes this line onto the current graph, the one that graphs
the three points. In other words, the new graph will show both the points
and the line, as in Figure 12-2.


Figure 12-2: Usingabline()


Graphics 263
Free download pdf