Add lines and smooth curves to scatterplots
Example 1
 plot(urb,infmor)
 abline(lsfit(urb,infmor),col="red")
 abline(line(urb,infmor), col="blue")

Produces a plot and adds a red least squares and a blue resistant line to the scatterplot. abline() adds a line to the current graphic. It gets the slope and the intercept to use from the lsfit(), respectively line(). As explained in detail in the document on the resistant line line() function, all regression procedures like lsfit() ("Least squares fit"), lm() ("Linear model") or line() (resistant line) produce "structures" that graphical functions can use for their purpose, in this case abline() extract the slope and intercept from the structure returned by the corresponding functions.

Example 2: Adding a smooth curve
 plot(urb,infmor)
 lines(lowess(urb,infmor))

The lowess() function returns a structure that contains two vectors x and y than can be used directly by the lines() function (adds points connected by a line segment).

Example 3; Smooth curves on scatterplot matrices

It is of course also possible to add smooth curves to co-plots] and [scatterplot matrices (both documents contain an example)

## create a subset data frame with 4 variables
mat1=subset(world,,select=c("infmor","urb","gnpcap","lit"))

pairs(mat1,panel=panel.smooth)
pairs(mat1,panel = panel.smooth,span=0.05)
pairs(mat1,upper.panel=panel.smooth,pch=".", span=0.1,col.line="blue")

All three command lines use the panel.smoothfunction, adding a lowess curve to each scatterplot.

  1. Default lowess smooth
  2. Specifies as span of .1 (fraction of observations to include in the smoothing window)
  3. Different span, changes old the marker symbol and the colour of the line; the lowess curve is only added to the upper.panel

Note that when the span= argument is present, you get warnings that span is not a graphical parameter, which is correct, it is however a parameter for the smoothing procedure and is correctly passed to it. You can safely ignore the warnings,

Adding a smooth curve and a regression line
require(car)
pairs(mat1,panel=panel.car,pch=".",col="blue")

The car packages contains a panel.car function that adds both a lowess curve and a regression line.

Your own function

You can also add your own lines and curves by writing your own function.

 twolines = function(x,y) {
    points(x,y,pch=".")
    abline(line(x,y),col="red")
    abline(lsfit(x,y),col="blue")
    }

Defines a function twolinesthat adds both a red resistant line and a blue least squares line.Définissons d'abord une fonction :

You can then use it in various places

plot(urb,infmor)
twolines(urb,infmor)

Add the two lines to a scatterplot

pairs(mat1,panel = twolines)

Add lines etc to the lattice plots