Use locator()
, a function that allows you to get the coordinates of the mouse pointer when clicking on a plot. Then use
plot(cars)
xy <- locator(n=2)
lines(xy, col="red", lwd=5)
lm(y~x, xy)
abline(coef(lm(y~x, xy)))
coef(lm(y~x, xy))
(Intercept) x
33.142094 1.529687
Of course the correct way of fitting lines through data is to use a proper model. Here is how you can do it with lm
:
abline(coef(lm(dist~speed, cars)), col="blue")
I made the following graph with this code:
- The thick red line is the line connecting my two mouse clicks
- The black line is the
abline
through these points
- The blue line is the line of best fit produced by
lm

Warning 1: locator
only works on some graphics devices. See ?locator
for more details.
Warning 2: Drawing lines of fit by hand could well be a really stupid idea. Use a regression function like lm
or a smoothing function like loess
instead.