# define a smooth 'true' function
# (proportional to a sum of two beta densities)

fun<-function(x) {2 * (0.6 * dbeta(x, 12, 7) + 0.4 * dbeta(x, 3, 11))}

# generate random x, and y as a noisy version of fun(x);
# plot points, and true curve on a fine grid

x<-sort(runif(100)); y<-fun(x)+rnorm(100)
xgrid<-(0:400)/400; ygridt<-fun(xgrid)
plot(x,y); lines(xgrid,ygridt,lty=2)

# fit cubic smoothing splines, default (GCV) tuning parameter

library(modreg)
spl.fit<-smooth.spline(x,y)
lines(predict(spl.fit,xgrid))

# plot cubic smoothing splines for 2 to 12 df

plot(x,y)
for(df in 2:12) lines(predict(smooth.spline(x,y,df=df),xgrid))

# plot least squares polynomials for 2 to 12 df

plot(x,y)
for(deg in 1:11) lines(x,lm(y~poly(x,deg))$fit)

# plot a selection of other smooths for these data

plot(x,y)
lines(ksmooth(x,y,kernel="normal",band=0.1,x.points=xgrid))
lines(lowess(x,y,f=0.2),lty=2)
lines(supsmu(x,y),lty=3)