Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

r - Showing equation of nls model with ggpmisc

R package ggpmisc can be used to show equation of lm model and poly model on ggplot2 (See here for reference). I wonder how I could show nls model equation results on ggplot2 using ggpmisc. 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...