문제

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

도움이 되었습니까?

해결책

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])
...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top