I am trying to annotate the ggplot graph with the equation y=ae^(bx)
I fitted a linear model log(y) ~ x
, and got the estimates for the coefficients: intercept and slope, and r^2 value:
a = round(exp(model$coefficients[1]), 2)
b = round(model$coefficients[2], 2)
r = round(summary(model)$r.squared, 2)
I would like to add the equation of the fitted model as an exponential to a ggplot graph, so lets assume my coefficients are:
a= -2
b= 0.5
r = 0.76
I used the example from: How to add the exponential regression equation and R2 on ggplot graph which uses the following code:
eq <- paste0('paste(y, " = ", italic(e^{', round(exp.mod$coefficients[2], 2),
"*x ~~ ~~ ", round(exp.mod$coefficients[1], 2),
'}), ~~~~~~~~R^2~ "="~', round(summary(exp.mod)$r.squared, 2), ")")
but this gives a bit different formula (y=e^(ax b)), I tried to rearrange it, but none of the attempts were successful
I also tried similar thing as shown here: Annotate exponential function ggplot2 but they used constants for their equation and I have variables, so I could not figure out how to replace numbers with variables
In the end, to add the equation to the plot, I tried to use the following line:
ggplot()
annotate("text", aes(x=3, y=11), label = "y == a*e^{b*x}", parse =TRUE)
CodePudding user response:
There are to problems with your last line of code: 1) annotate()
does not support mapping of variables in data to aesthetics, one just the constant values as arguments; 2) the whole superscript, including the minus symbol must go inside the curly brackets. (The equation looks a bit nicer replacing the *
in front of the exponential by ~
to add a bit of space, but this is optional.)
library(ggplot2)
ggplot()
annotate("text", x=3, y=11, label = "y == 13.048*e^{-0.697*x}", parse =TRUE)
Expressions have a tricky syntax. I used here your assumed values. I changed r
into r.squared
for clarity.
a= -2
b= 0.5
r.squared = 0.76
eq <- paste0('y~`=`~', a,
'~e^{', b ,
'*x}*"; "*R^2~`=`~', r.squared)
ggplot()
annotate("text", x=3, y=11, label = eq, parse =TRUE)
Created on 2021-09-21 by the reprex package (v2.0.1)