It is also possible to add the equation using package 'ggpmisc', assembling the character string to be parsed with paste()
or sprintf()
. In this answer I will use sprintf()
. I answer the question using the example it included. I do not show this in this answer, but this approach supports grouping and facets. The drawback is that the model is fit twice, once to draw the fitted line and once to add the equation.
To find the names of the variables returned by stat_fit_tidy()
I used geom_debug()
from package 'gginnards', although the names even if dependent on the model formula and method are rather easy to predict. Instead of adding a plot layer geom_debug()
echoes is data
input to the R console. Next, once we know the names of the variables we wish to use in the label, we can assemble the string to be parsed as an R expression.
When assembling the label with sprintf()
one needs to escape the %
characters to be returned unchanged as %%
, so the multiplication sign %*%
becomes %%*%%
. It is possible, and in this case useful to embed character strings in the R expression, but we need to escape the embedded quotation marks as \"
.
library(tidyverse)
library(ggpmisc)
#> Loading required package: ggpp
#>
#> Attaching package: 'ggpp'
#> The following object is masked from 'package:ggplot2':
#>
#> annotate
library(gginnards)
args <- list(formula = y ~ k * e ^ x,
start = list(k = 1, e = 2))
# we find the names of computed values
ggplot(mtcars, aes(wt, mpg)) +
stat_fit_tidy(method = "nls",
method.args = args,
geom = "debug")
#> Input 'data' to 'draw_panel()':
#> npcx npcy k_estimate e_estimate k_se e_se k_stat e_stat
#> 1 NA NA 49.65969 0.7455911 3.788755 0.01985924 13.10713 37.54378
#> k_p.value e_p.value x y fm.class fm.method fm.formula
#> 1 5.963165e-14 8.861929e-27 1.70855 32.725 nls nls y ~ k * e^x
#> fm.formula.chr PANEL group
#> 1 y ~ k * e^x 1 -1
# plot with formula
ggplot(mtcars, aes(wt, mpg)) +
geom_point() +
stat_fit_augment(method = "nls",
method.args = args) +
stat_fit_tidy(method = "nls",
method.args = args,
label.x = "right",
label.y = "top",
aes(label = sprintf("\"mpg\"~`=`~%.3g %%*%% %.3g^{\"wt\"}",
after_stat(k_estimate),
after_stat(e_estimate))),
parse = TRUE )
Created on 2022-09-02 with reprex v2.0.2
check_subclass()
: ! Can't findgeom
called 'debug' – Almeria