I am trying to fit a sinusoidal curve to data using the following code. I'm not sure why its turning out funky where the lines seemingly go from the observation at 17 to 9 then 9 to 20 and back to 12. I'd also like the sinusoidal curve to extend across the full 24 hours. If you can do this in ggplot2 that would be fantastic. Thanks!
Test_case <- structure(list(TEST_RESULT = c(1.31, 65.44, 8.59, 9.91), Time = c(17,
9, 20, 12)), row.names = c(NA, -4L), class = c("tbl_df", "tbl",
"data.frame"))
Time <- test_case$Time
test_result <- test_case$TEST_RESULT
xc<-cos(2*pi*Time/24)
xs<-sin(2*pi*Time/24)
fit.lm <- lm(test_result ~ xc+xs)
fit <- fitted(fit.lm)
# find predictions for original time series
pred <- predict(fit.lm, newdata=data.frame(Time=Time))
plot(test_result ~ Time, data= test_case, xlim=c(1, 24), ylim=c(0,500))
lines(Time, pred, col="blue")
Make sure that the Time variable appears in the formula and is not hidden by the xc and xs variables. Also be sure that the times used in the prediction are in order, i.e. 0:23 is in ascending order. On the other hand, the input data need not be in order since we are only plotting it as points so the order the input data is plotted does not matter.
Thus using test_case
from the question we have:
fit.lm <- lm(test_result ~ cos(2*pi*Time/24) + sin(2*pi*Time/24), test_case)
Time2 <- 0:23
pred2 <- predict(fit.lm, newdata = list(Time = Time2))
plot(test_result ~ Time, data = test_case, xlim = c(1, 24), ylim = c(0, 500))
lines(pred2 ~ Time2, col = "blue")