如何在 ggplot 上的 activity 数据上拟合正弦波

How to fit a sine wave over activity data in r on ggplot

我有来自大型数据集的 activity 数据,我试图拟合正弦波以找到 activity 的波峰和波谷的相应时间点。数据不一定是正弦曲线,这可能是个问题,但我还是想拟合一条曲线。在节奏数据和数据分析方面,我也是新手,所以请随时提供新信息或建议。这是link第一周一只老鼠的数据https://www.dropbox.com/s/m08vk7ovij2wcnb/stack_sine_dt.csv?dl=0

          id  eday   act      t
       <fctr> <int> <num>  <num>
    1:   M001     1    17  86400
    2:   M001     1    10  86460
    3:   M001     1    13  86520
    4:   M001     1    14  86580
    5:   M001     1    24  86640
   ---                          
10076:   M001     7     0 690900
10077:   M001     7     1 690960
10078:   M001     7     0 691020
10079:   M001     7     0 691080
10080:   M001     7     0 691140

我遵循了 this post here 的指导并得到了一个不错的图表,尽管波浪似乎并不是每天都有波峰和波谷。我希望将其叠加在 ggplot 散点图上。

# here I fit a wave using lm()
lmfit <- lm(data = dt,
            act ~ sin(2*pi*t/365.25) + cos(2*pi*t/365.25))
# then get relevant parameters
b0 <- coef(lmfit)[1]
alpha <- coef(lmfit)[2]
beta <- coef(lmfit)[3]

r <- sqrt(alpha^2 + beta^2)
phi <- atan2(beta, alpha)

# and fit it to some base plots
par(mfrow=c(1,2))
curve(b0 + r * sin(x + phi), 0, 2*pi, lwd=3, col="Gray",
      main="Overplotted Graphs", xlab="x", ylab="y")
curve(b0 + alpha * sin(x) + beta * cos(x), lwd=3, lty=3, col="Red", add=TRUE)
curve(b0 + r * sin(x + phi) - (b0 + alpha * sin(x) + beta * cos(x)), 
      0, 2*pi, n=257, lwd=3, col="Gray", main="Difference", xlab="x", y="")

这是基本图的输出以及我想放置正弦波的 ggplot 散点图。

像这样你可以在ggplot散点图上叠加拟合曲线(我改编了here的代码):

library(broom)
library(dplyr)
# here I fit a wave using lm()
lmfit <- lm(data = dt,
            act ~ sin(2*pi*t/36500.25))

bind_cols(dt, lmfit %>% augment) %>% 
  ggplot(aes(t, act...3)) +
  geom_point() +
  geom_ribbon(aes(ymin = .fitted - 1.96*.se.fit, ymax = .fitted + 1.96*.se.fit), alpha = 0.5) + geom_line(mapping = aes(y = .fitted), col = "red")

您的主要问题是您的时间以秒为单位并且想要以日为单位,但是您使用的代码假定时间以天为单位并且您想要以年为单位...

x <- read.csv("stack_sine_dt.csv")

secs_per_day <- 24*3600
x$tday <- x$t/secs_per_day
lmfit <- lm(data = x,
            act ~ sin(2*pi*tday) + cos(2*pi*tday))
b0 <- coef(lmfit)[1]
alpha <- coef(lmfit)[2]
beta <- coef(lmfit)[3]

pframe <- data.frame(tday=seq(min(x$tday),max(x$tday),length=501))
pframe$act <- predict(lmfit,newdata=pframe)

library(ggplot2); theme_set(theme_bw())
ggplot(x,aes(tday,act))+
    geom_point(alpha=0.2) + geom_line(data=pframe,colour="red")