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