如何将指数衰减的时间序列模型叠加到ggplot2图形中?

Mit*_*ops 0 r time-series ggplot2 exponential

我试图将指数衰减线(带有误差线)绘制到价格信息的ggplot中的散点图上.我目前有这个:

f2 <- ggplot(data, aes(x=date, y=cost) ) +
    geom_point(aes(y = cost), colour="red", size=2) +
    geom_smooth(se=T, method="lm", formula=y~x) +
#   geom_smooth(se=T) +
    theme_bw() +
    xlab("Time") + 
    scale_y_log10("Price over time") +
    opts(title="The Falling Price over time")
print(f2)
Run Code Online (Sandbox Code Playgroud)

关键是在geom_smooth命令中,formula=y~x 尽管这看起来像一个线性模型,ggplot似乎会自动检测我的scale_y_log10并记录它.

现在,我的问题是日期是日期数据类型.我想我需要将它转换为秒,因为t = 0才能应用表格的指数衰减模型y = Ae^-(bx).

我相信这是因为当我尝试y = exp(x)之类的东西时,我得到一条消息,我认为(?)告诉我,我不能接受日期的指数.它写道:

Error in lm.wfit(x, y, w, offset = offset, singular.ok = singular.ok, : NA/NaN/Inf in foreign function call (arg 1)

但是,log(y) = x正常工作.(y是数字数据类型,x是日期.)

有没有一种方便的方法可以在geom_smooth(公式=公式)函数调用中的ggplot图中拟合指数增长/衰减时间序列模型?

Ben*_*ker 5

这似乎有效,虽然我不知道真实/混乱数据会有多么挑剔:

set.seed(101)
dat <- data.frame(d=seq.Date(as.Date("2010-01-01"),
                         as.Date("2010-12-31"),by="1 day"),
                y=rnorm(365,mean=exp(5-(1:365)/100),sd=5))

library(ggplot2)
g1 <- ggplot(dat,aes(x=d,y=y))+geom_point()+expand_limits(y=0)
g1+geom_smooth(method="glm",family=gaussian(link="log"),
               start=c(5,0))
Run Code Online (Sandbox Code Playgroud)