How to fit exponential model in R and print correct y=ab^(x) equation

Viewed 18

I'm trying to fit an exponential model on this datased.

y <- c(0.04, 0.04, 0.03, 0.03, 0.04, 0.03, 0.02, 0.03, 0.03, 0.02, 0.08, 0.04, 0.04, 0.07, 0.04, 0.05, 0.12, 0.05, 0.13, 0.11, 0.11, 0.33, 0.03, 0.08)
x <- c(3.75, 4.25, 1.77, 4.24, 2.99, 3.82, 1.85, 3.17, 2.64, 2.10, 4.23, 3.81, 3.55, 3.73, 3.85, 4.31, 4.35, 3.80, 7.26, 5.91, 8.15, 8.56, 7.49, 8.12)
df <- data.frame(x, y)

ggplot(data = df, aes(x=x,y=y)) + 
  geom_point(size = 3) + 
  stat_smooth(method = "lm", formula =  y ~ exp(x))+
  stat_poly_eq(label.x=0.1, label.y=0.85,
                aes(x=x,y=y,label = paste(..eq.label..)), formula =  y ~ exp(x), 
               parse = TRUE, size = 3.5)+
  stat_poly_eq(label.x=0.1, label.y=0.8, 
               aes(x=x,y=y,label = paste(..rr.label..)), formula =  y ~ exp(x),
               parse = TRUE, size = 3.5)+
  theme_classic()

I'd also need to plot it, and so far I was able to fit a proper smooth together with a correct r2 I think. however, I can't seem to be able to print the correct exponential function on the plot, at least by using stat_poly_eq() function.

This only seem to be able to print a function in a linear way, althgough I specify the formula = y ~ exp(x), argument. Does anyone know how I could have the right exp function on the plot? Thank you!

1 Answers

Here is a solution.

  • define a format string, eq_fmt, to make the plot code easier to read;
  • use the coefficients names b_0 and b_1 like below. This will not write the equation as a*b^x, the base is the base of natural logarithms;
  • and set output.type = "numeric".
library(ggplot2)
library(ggpmisc)
#> Loading required package: ggpp
#> 
#> Attaching package: 'ggpp'
#> The following object is masked from 'package:ggplot2':
#> 
#>     annotate

y <- c(0.04, 0.04, 0.03, 0.03, 0.04, 0.03, 0.02, 0.03, 0.03, 0.02, 0.08, 0.04, 0.04, 0.07, 0.04, 0.05, 0.12, 0.05, 0.13, 0.11, 0.11, 0.33, 0.03, 0.08)
x <- c(3.75, 4.25, 1.77, 4.24, 2.99, 3.82, 1.85, 3.17, 2.64, 2.10, 4.23, 3.81, 3.55, 3.73, 3.85, 4.31, 4.35, 3.80, 7.26, 5.91, 8.15, 8.56, 7.49, 8.12)
df <- data.frame(x, y)

eq_fmt <- "`y`~`=`~%.3g~italic(e)^{%.3g~`x`}"
ggplot(data = df, aes(x=x,y=y)) + 
  geom_point(size = 3) + 
  stat_smooth(method = "lm", formula =  y ~ exp(x))+
  stat_poly_eq(mapping = aes(x = x, y = y,
                             label = sprintf(eq_fmt, 
                                             after_stat(b_0), 
                                             after_stat(b_1))), 
               label.x = 0.1, label.y = 0.85,
               formula =  y ~ exp(x), 
               output.type = "numeric",
               parse = TRUE
  ) +
  stat_poly_eq(label.x=0.1, label.y=0.8, 
               aes(x=x,y=y,label = paste(..rr.label..)), formula =  y ~ exp(x),
               parse = TRUE, size = 3.5)+
  theme_classic()

Created on 2022-09-22 with reprex v2.0.2

Related