Showing equation of nls model with ggpmisc

2019-06-15 07:58发布

R package ggpmisc can be used to show equation of lm model and poly model on ggplot2 (See here for reference). Wonder how to show nls model equation results on ggplot2 using ggmisc. Below is my MWE.

library(ggpmisc)
args <- list(formula = y ~ k * e ^ x,
             start = list(k = 1, e = 2))
ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  stat_fit_augment(method = "nls",
                   method.args = args)

1条回答
SAY GOODBYE
2楼-- · 2019-06-15 08:25

Inspired by the post you linked. Use geom_text to add the label after extracting parameters.

nlsFit <-
  nls(formula = mpg ~ k * e ^ wt,
      start = list(k = 1, e = 2),
      data = mtcars)

nlsParams <-
  nlsFit$m$getAllPars()

nlsEqn <-
  substitute(italic(y) == k %.% e ^ italic(x), 
             list(k = format(nlsParams['k'], digits = 4), 
                  e = format(nlsParams['e'], digits = 2)))

nlsTxt <-
  as.character(as.expression(nlsEqn))

ggplot(mtcars, aes(wt, mpg)) +
  geom_point() +
  stat_fit_augment(method = "nls",
                   method.args = args) + 
  geom_text(x = 5, y = 30, label = nlsTxt, parse = TRUE)
查看更多
登录 后发表回答