loess line not plotting correctly

2019-02-17 16:44发布

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

1条回答
Lonely孤独者°
2楼-- · 2019-02-17 17:17

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])
...
查看更多
登录 后发表回答