Home > Net >  R equivalent of excel exponential trendline (including equation)
R equivalent of excel exponential trendline (including equation)

Time:09-29

The attached picture shows the exponential curve fitting and the exponential equation for this set of data I have. However, I have 219 samples just like the picture that I would like to code in r & get the value for the exponential parameters (the power and the constant). I have tried lm() and nls(). With lm(), I realized in doesn't give me the same exponential format as excel. By that I mean exponential function including e (refer to the equation in the attached image). With nls() the values seem so small to me & don't match what excel gives me.

enter image description here

CodePudding user response:

Difficult to say without a reproducible example, but your code could be something like this:

library(ggplot2)

mod <- nls(y ~ a * exp(b * x), data = df, start = list(a = 8, b = 0.1))

a <- round(coef(mod)["a"], 2)
b <- round(coef(mod)["b"], 4)
Formula <- bquote(y == .(a) * e^{.(b)*x})

ggplot(df, aes(as.numeric(bins) * 10, y))  
  geom_point(stat = "summary", fun = "mean", col = "orange", 
             shape = 15, size = 5)  
  theme_minimal(base_size = 20)  
  geom_smooth(aes(group = 1), method = nls,
              formula = y ~ a * exp(b * x), 
              method.args = list(start = list(a = 8, b = 0.1)),
              se = FALSE, color = "black", linetype = 2)  
  annotate(geom = "text", label = Formula, x = 20, y = 70, size = 6)  
  scale_x_continuous(breaks = 0:10 * 10, name = "x")  
  theme(panel.grid.major.x = element_blank(),
        panel.grid.minor.x = element_blank(),
        axis.ticks = element_line())

Created on 2022-09-28 with Plot

  • Related