How to fit a smooth curve to my data in R?
Maybe smooth.spline is an option, You can set a smoothing parameter (typically between 0 and 1) here
smoothingSpline = smooth.spline(x, y, spar=0.35)
plot(x,y)
lines(smoothingSpline)
you can also use predict on smooth.spline objects. The function comes with base R, see ?smooth.spline for details.
In order to get it REALLY smoooth...
x <- 1:10
y <- c(2,4,6,8,7,8,14,16,18,20)
lo <- loess(y~x)
plot(x,y)
xl <- seq(min(x),max(x), (max(x) - min(x))/1000)
lines(xl, predict(lo,xl), col='red', lwd=2)
This style interpolates lots of extra points and gets you a curve that is very smooth. It also appears to be the the approach that ggplot takes. If the standard level of smoothness is fine you can just use.
scatter.smooth(x, y)
I like loess()
a lot for smoothing:
x <- 1:10
y <- c(2,4,6,8,7,12,14,16,18,20)
lo <- loess(y~x)
plot(x,y)
lines(predict(lo), col='red', lwd=2)
Venables and Ripley's MASS book has an entire section on smoothing that also covers splines and polynomials -- but loess()
is just about everybody's favourite.