Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fit a smooth curve to my data in R?

I'm trying to draw a smooth curve in R. I have the following simple toy data:

> x  [1]  1  2  3  4  5  6  7  8  9 10 > y  [1]  2  4  6  8  7 12 14 16 18 20 

Now when I plot it with a standard command it looks bumpy and edgy, of course:

> plot(x,y, type='l', lwd=2, col='red') 

How can I make the curve smooth so that the 3 edges are rounded using estimated values? I know there are many methods to fit a smooth curve but I'm not sure which one would be most appropriate for this type of curve and how you would write it in R.

like image 562
Frank Avatar asked Aug 13 '10 20:08

Frank


People also ask

How do I fit a smooth curve in R?

To fit a smooth curve to the data, you can use the loess() function that fits a polynomial surface determined by one or more numerical predictors, using local fitting.

How do I fit a curve to a graph in R?

To fit a curve to some data frame in the R Language we first visualize the data with the help of a basic scatter plot. In the R language, we can create a basic scatter plot by using the plot() function. where, df: determines the data frame to be used.

How do you make a smooth scatter plot in R?

In R, the smoothed curve can be estimated using the loess. smooth() function or we can generate the plot using the scatter. smooth() function directly. In the example below, we add both a regression line and a smoothed line to the scatter plot between age and hvltt variable.

What is a smoother in R?

smoother: Functions Relating to the Smoothing of Numerical Data. A collection of methods for smoothing numerical data, commencing with a port of the Matlab gaussian window smoothing function. In addition, several functions typically used in smoothing of financial data are included. Version: 1.1.


2 Answers

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.

like image 100
Dirk Eddelbuettel Avatar answered Oct 19 '22 07:10

Dirk Eddelbuettel


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.

like image 38
Karsten W. Avatar answered Oct 19 '22 06:10

Karsten W.