在R中用LOESS拟合一条线 [英] Fit a line with LOESS in R
问题描述
我有一个包含一些点的数据集,并且想在上面放一条线.我尝试使用loess
函数.不幸的是,我得到了非常奇怪的结果.参见下面的情节.我希望有一条线能够贯穿点和整个情节.我该如何实现?
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?
如何复制它:
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!
推荐答案
您已经针对y
而不是针对x
绘制了拟合值.同样,您将需要在绘制线之前对x值进行排序.试试这个:
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)
这篇关于在R中用LOESS拟合一条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!