问题
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:
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])
...
来源:https://stackoverflow.com/questions/10007830/loess-line-not-plotting-correctly