How can I overlay timeseries models for exponential decay into ggplot2 graphics?

Go To


I'm trying to plot an exponential decay line (with error bars) onto a scatterplot in ggplot of price information over time. I currently have this:

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")

The key line is in the geom_smooth command, of formula=y~x Although this looks like a linear model, ggplot seems to automatically detect my scale_y_log10 and log it.

Now, my issue here is that date is a date data type. I think I need to convert it to seconds since t=0 to be able to apply an exponential decay model of the form y = Ae^-(bx).

I believe this because when I tried things like y = exp(x), I get a message that I think(?) is telling me I can't take exponents of dates. It reads:

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

However, log(y) = x works correctly. (y is a numeric data type, x is a date.)

Is there a convenient way to fit exponential growth/decay time series models within ggplot plots in the geom_smooth(formula=formula) function call?

2012-04-03 20:30
by Mittenchops
maybe geom_smooth(method="glm",family=gaussian(link="log")) - Ben Bolker 2012-04-03 20:33
(a reproducible example would be nice. - Ben Bolker 2012-04-03 20:40
That looks promising---do you know the syntax for specifying starting values? When I tried with defaults, I saw Error in eval(expr, envir, enclos) : cannot find valid starting values: please specify some Mittenchops 2012-04-03 20:42


This appears to work, although I don't know how finicky it will be with real/messy data:

dat <- data.frame(d=seq.Date(as.Date("2010-01-01"),
                         as.Date("2010-12-31"),by="1 day"),

g1 <- ggplot(dat,aes(x=d,y=y))+geom_point()+expand_limits(y=0)
2012-04-03 20:48
by Ben Bolker
Perfect! It turns out, this doesn't fit my data at all, but this is definitely the right answer. = - Mittenchops 2012-04-04 05:56