【问题标题】:Showing equation of nls model with ggpmisc用 ggpmisc 显示 nls 模型的方程
【发布时间】:2016-12-05 18:39:16
【问题描述】:

R 包ggpmisc 可用于在ggplot2 上显示lm 模型和poly 模型的方程(See here 供参考)。我想知道如何使用ggpmisc 在ggplot2 上显示nls 模型方程结果。下面是我的 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)

【问题讨论】:

    标签: r ggplot2 lm nls ggpmisc


    【解决方案1】:

    受您链接的帖子的启发。提取参数后使用geom_text添加标签。

    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)
    

    【讨论】:

      【解决方案2】:

      在这里,我使用当前的 CRAN ggpmisc (v 0.3.8) 展示了使用 ggpmisc 添加到绘图的组的 nls。这是小插图的变体/修改,其中“stat_fit_tidy()”使用 michaelis-menten 拟合,发现 here。 输出如下所示:

      library(tidyverse)
      library(tidymodels)
      library(ggpmisc)
      
      my_exp_formula <-  y ~ a * exp(b*x-0)
      # if x has large values (i.e. >700), subtract the minimum
      # see https://stackoverflow.com/a/41108403/4927395
      
      #example with nls, shows the data returned
      o <- nls(1/rate ~ a * exp(b*conc-0), data = Puromycin, start = list(a = 1, b = 2))
      o
      tidy(o)
      
      ggplot(Puromycin, aes(conc, 1/rate, colour = state)) +
        geom_point() +
        geom_smooth(method = "nls", 
                    formula = my_exp_formula,
                    se = FALSE) +
        stat_fit_tidy(method = "nls", 
                      method.args = list(formula = my_exp_formula),
                      label.x = "right",
                      label.y = "top",
                      aes(label = paste("a~`=`~", signif(stat(a_estimate), digits = 3),
                                        "%+-%", signif(stat(a_se), digits = 2),
                                        "~~~~b~`=`~", signif(stat(b_estimate), digits = 3),
                                        "%+-%", signif(stat(b_se), digits = 2),
                                        sep = "")),
                      parse = TRUE)
      ggsave("exp plot.png")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-05
        • 2020-05-16
        • 1970-01-01
        • 2022-11-09
        • 1970-01-01
        • 1970-01-01
        • 2021-02-16
        相关资源
        最近更新 更多