6

I'm having trouble fitting a loess smooth plus confidence limits to a scatterplot of residuals.

My model is height ~ weight + chest circumference. To check linearity of chest circumference, I've fitted a model without chest circumference (i.e. height ~ weight), and plotted the residuals of this model against chest circumference. So far so good. I then tried to use loess() and predict() to plot a loess line, plus confidence limits. The result looks like this (in the picture I've only plotted the central line, but the CI lines look the same):

Loess problem in scatterplot

The points are correct (when I plot the loess fit as points it looks right), but for some reason the line is not being drawn how I expect. My code is below:

# bf.red = data set; mod.nch = model; chestc = chest circumference;
# loess = loess model; lo.pred = predict loess

plot(bf.red$chestc           #Chest circumference
 ,residuals(mod.nch))    #Residuals from height ~ weight model

loess <- loess(mod.nch$residuals ~ bf.red$chestc)
lo.pred <- predict(loess, se=T)

lines(bf.red$chestc,lo.pred$fit,pch=2) #Main line
lines(bf.red$chestc,lo.pred$fit+2*lo.pred$s, lty=2) #rough & ready CI
lines(bf.red$chestc,lo.pred$fit-2*lo.pred$s, lty=2)

Hope you can help. Many thanks,

Mat

plannapus
  • 18,529
  • 4
  • 72
  • 94
MatW
  • 305
  • 3
  • 7

1 Answers1

7

lines connects the points in the order in which they appear, which is sometimes undesirable. You can sort them as follows:

i <- order(bf.red$chestc)
lines(bf.red$chestc[i], lo.pred$fit[i])
...
Vincent Zoonekynd
  • 31,893
  • 5
  • 69
  • 78
  • p.s. This post is now the top search result on Google for "r lines not plotting correct order" which is what I typed in before I asked the question, but couldn't find a good answer. The next person who has this problem _will_ find a good answer! – MatW Apr 04 '12 at 13:52