如何在ggplot上的r的活动数据上拟合正弦波

问题描述 投票:1回答:2

我有一个来自大型数据集的活动数据,我正试图拟合一个正弦波来查找活动高峰和低谷的相应时间点。数据不一定是正弦曲线的,这可能是一个问题,但是我仍然想拟合一条曲线。我还是节奏数据和数据分析的新手,请随时提供新的信息或建议。这是第一周内一只鼠标的数据链接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散点图。

enter image description here enter image description here

r ggplot2 trigonometry
2个回答
0
投票

像这样,您可以将拟合曲线叠加在ggplot散点图上(我改编自here中的代码):


0
投票

您的主要问题是,您有以秒为单位的时间,并且需要一个每日时间段,但是您所使用的代码假定时间以天为单位,并且您想要一个年度时间...]

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")
© www.soinside.com 2019 - 2024. All rights reserved.