data(anscombe) help(anscombe) attach(anscombe) par(mfrow=c(2,2)) plot(x1,y1) plot(x2,y2) plot(x3,y3) plot(x4,y4) #Scatterplot smooth demo x=seq(1,10,by=.4) nx=length(x) #Save y generated by the following code #y=.5-2*log(x)+5*sqrt(x)+rnorm(nx) y=c(6.4,7.0,6.2,7.7,6.4,6.7,7.6,7.6,7.7,8.0,10.1,10.2,10.0,12.3,11.2,10.0,8.2,10.0,8.6,8.9,9.2,9.7,10.2) plot(x,y) #For each x, draw the regression line for all observations in (x-3,x+3). We will ignore weights for this demo. for(i in 1:nx){ xreg=x[abs(x-x[i])<3] yreg=y[abs(x-x[i])<3] wreg=lm(yreg~xreg) a=wreg$coef[1] b=wreg$coef[2] lines(c(x[i]-3,x[i]+3),c(a+b*(x[i]-3),a+b*(x[i]+3)),col=i) } title("Local least squares lines") #Keep the fitted value only at each x[i] plot(x,y) for(i in 1:nx){ xreg=x[abs(x-x[i])<3] yreg=y[abs(x-x[i])<3] wreg=lm(yreg~xreg) a=wreg$coef[1] b=wreg$coef[2] points(x[i],a+b*x[i],col="red",cex=1.5) } title("Fitted values for each centerpoint of local least squares") #Connect the dots for the fitted line plot(x,y) yhat=rep(0,nx) for(i in 1:nx){ xreg=x[abs(x-x[i])<3] yreg=y[abs(x-x[i])<3] wreg=lm(yreg~xreg) a=wreg$coef[1] b=wreg$coef[2] yhat[i]=a+b*x[i] } lines(x,yhat,col="red",lwd=2) title("Local regression") #Try a smaller window yhats=rep(0,nx) for(i in 1:nx){ xreg=x[abs(x-x[i])<1.5] yreg=y[abs(x-x[i])<1.5] wreg=lm(yreg~xreg) a=wreg$coef[1] b=wreg$coef[2] yhats[i]=a+b*x[i] } lines(x,yhats,col="blue",lwd=2) legend(5,7.5,c("Window=3","Window=1.5"),lwd=c(2,2),col=c("red","blue"),cex=.8)