Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fit a line with LOESS in R

Tags:

I have a data set with some points in it and want to fit a line on it. I tried it with the loess function. Unfortunately I get very strange results. See the plot bellow. I expect a line that goes more through the points and over the whole plot. How can I achieve that? plot

How to reproduce it:

Download the dataset from https://www.dropbox.com/s/ud32tbptyvjsnp4/data.R?dl=1 (only two kb) and use this code:

load(url('https://www.dropbox.com/s/ud32tbptyvjsnp4/data.R?dl=1')) lw1 = loess(y ~ x,data=data) plot(y ~ x, data=data,pch=19,cex=0.1) lines(data$y,lw1$fitted,col="blue",lwd=3) 

Any help is greatly appreciated. Thanks!

like image 797
leo Avatar asked Mar 11 '13 09:03

leo


People also ask

What is a loess line in R?

Loess Regression is the most common method used to smoothen a volatile time series. It is a non-parametric methods where least squares regression is performed in localized subsets, which makes it a suitable candidate for smoothing any numerical vector.

What is loess fit line?

LOWESS (Locally Weighted Scatterplot Smoothing), sometimes called LOESS (locally weighted smoothing), is a popular tool used in regression analysis that creates a smooth line through a timeplot or scatter plot to help you to see relationship between variables and foresee trends.

How do you fit a smooth curve to R data?

1 Answer. 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.


2 Answers

You've plotted fitted values against y instead of against x. Also, you will need to order the x values before plotting a line. Try this:

lw1 <- loess(y ~ x,data=data) plot(y ~ x, data=data,pch=19,cex=0.1) j <- order(data$x) lines(data$x[j],lw1$fitted[j],col="red",lwd=3) 

enter image description here

like image 125
Rob Hyndman Avatar answered Nov 14 '22 03:11

Rob Hyndman


Unfortunately the data are not available anymore, but an easier way how to fit a non-parametric line (Locally Weighted Scatterplot Smoothing or just a LOESS if you want) is to use following code:

scatter.smooth(y ~ x, span = 2/3, degree = 2) 

Note that you can play with parameters span and degree to get arbitrary smoothness.

like image 36
HonzaB Avatar answered Nov 14 '22 03:11

HonzaB