在R中使用lm和nls进行正弦曲线拟合 [英] Sine curve fit using lm and nls in R
问题描述
我是曲线拟合的初学者,Stackoverflow上的几篇文章确实对我有所帮助。
我尝试使用 lm
和 nls
,但这两种方法都显示出奇怪的拟合度,如下所示。谁能指出我哪里出了问题。我怀疑与时间有关,但无法正确处理。可以从帖子)]:
数据<-已读.table(file = 900days.txt,header = TRUE,sep =)
时间<-数据$时间
温度<-数据$温度
xc< -cos(2 * pi *时间/ 366)
xs< -sin(2 * pi *时间/ 366)
fit.lm<-lm(温度〜xc + xs)
#访问拟合序列(用于绘图)
fit<-拟合(fit.lm)
#查找原始时间序列的预测
pred< ;-预测(fit.lm,newdata = data.frame(Time = Time))
图(温度〜Time,data = Data,xlim = c(1,900))
l ines(fit,col = red)
行(时间,pred,col = blue)
这给了我:
您可能希望的是哪个。
I am a beginner in curve fitting and several posts on Stackoverflow really helped me.
I tried to fit a sine curve to my data using lm
and nls
but both methods show a strange fit as shown below. Could anyone point out where I went wrong. I would suspect something to do with time but could not get it right. My data can be accessed from here.
data <- read.table(file="900days.txt", header=TRUE, sep="")
time<-data$time
temperature<-data$temperature
#lm fitting
xc<-cos(2*pi*time/366)
xs<-sin(2*pi*time/366)
fit.lm<-lm(temperature~xc+xs)
summary(fit.lm)
plot(temp~time, data=data, xlim=c(1, 900))
par(new=TRUE)
plot(fit.lm$fitted, type="l", col="red", xlim=c(1, 900), pch=19, ann=FALSE, xaxt="n",
yaxt="n")
#nls fitting
fit.nls<-nls(temp~C+alpha*sin(W*time+phi),
start=list(C=27.63415, alpha=27.886, W=0.0652, phi=14.9286))
summary(fit.nls)
plot(fit.nls$fitted, type="l", col="red", xlim=c(1, 900), pch=19, ann=FALSE, xaxt="n",
axt="n")
This is because the NA
values are removed from the data to be fit (and your data has quite a few of them); hence, when you plot fit.lm$fitted
the plot method is interpreting the index of that series as the 'x' values to plot it against.
Try this [note how I've changed variable names to prevent conflicts with the functions time
and data
(read this post)]:
Data <- read.table(file="900days.txt", header=TRUE, sep="")
Time <- Data$time
temperature <- Data$temperature
xc<-cos(2*pi*Time/366)
xs<-sin(2*pi*Time/366)
fit.lm <- lm(temperature~xc+xs)
# access the fitted series (for plotting)
fit <- fitted(fit.lm)
# find predictions for original time series
pred <- predict(fit.lm, newdata=data.frame(Time=Time))
plot(temperature ~ Time, data= Data, xlim=c(1, 900))
lines(fit, col="red")
lines(Time, pred, col="blue")
This gives me:
Which is probably what you were hoping for.
这篇关于在R中使用lm和nls进行正弦曲线拟合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!