Search code examples
rggplot2exponentialtrend

Add exponential trend line to ggplot


I have a dataset named daph

daph <- read.table(text = "t v 20 19 25 78.2 30 254.8 ",header = TRUE, sep = "")

and what I'm trying to do is adding an exponential trend line to a barplot with these values

ggplot(data=daph, aes(x=t, y=v, width=1)) + geom_bar(stat="identity", fill="steelblue") + theme_minimal(base_size=18) + geom_smooth(method = 'nls', formula = y ~ a * exp(b * x), se = FALSE, method.args = list(start = list(a = 1, b = 1)))

but it gives me an error message every time (singular gradient, roughly translated).

I suppose it's got something to do with my starting values, but I'm not enough into maths to understand a lot about this.

Maybe some of you can help me :)


Solution

  • nls are notoriously hard to fit. For your scenario, try providing better starting values or consider using the linear model instead, you can check it out in this post:

    lmfit = lm(log(v) ~ t,data=daph)
    A = coef(lmfit)[1]
    B = coef(lmfit)[2]
    
    ggplot(data=daph, aes(x=t, y=v, width=1)) +
    geom_bar(stat="identity", fill="steelblue") +
    theme_minimal(base_size=18) +
    geom_smooth(method = 'nls', formula = y ~ a * exp(b * x), 
    se = FALSE, method.args = list(start = list(a = A, b = B)))
    

    enter image description here

    The data:

    structure(list(t = c(9, 21, 29), v = c(19, 78.2, 254.8)), row.names = c(NA, 
    -3L), class = "data.frame")