【问题标题】:How to extract stat_smooth exponential fit parameters ggplot2如何提取stat_smooth指数拟合参数ggplot2
【发布时间】:2021-09-29 16:12:36
【问题描述】:

我已经尝试了这里找到的许多建议,但我就是想不通。

是否可以从符合 stat_smooth 的直线中提取方程 (y = a+exp(-b*x))?

这是一个数据示例:

df <-data_frame(Time = c(0.5,1,2,4,8,16,24), Concentration = c(1,0.5,0.2,0.05,0.02,0.01,0.001))


Plot <- ggplot(df, aes(x=Time, y=Concentration))+
  geom_point(size=2) + 
  stat_smooth(method = nls, formula = y ~ a*exp(-b *x), 
             se = FALSE, 
              method.args = list(start = c(a=10, b=0.01)))+
  theme_classic(base_size = 15) +
  labs(x=expression(Time (h)),
       y=expression(C[t]/C[0]))

我尝试使用 "stat_regline_equation" ,但是当我添加指数函数时它不起作用。

【问题讨论】:

  • 提取是什么意思?你想达到什么目标?
  • 我想把指数函数的a和b参数拿到线。

标签: r ggplot2 exponential model-fitting


【解决方案1】:

要从 ggplot 中提取数据,您可以使用: ggplot_build()

来自stat_smooth() 的值在ggplot_build(Plot)$data[[2]]

您可以将其分配给对象:build &lt;- ggplot_build(Plot)$data[[2]]

以下两个代码给出相同的结果

Plot <- ggplot(df, aes(x=Time, y=Concentration)) + geom_point(size=2) + 
  stat_smooth(method = nls, formula = y ~ a*exp(-b *x), se = FALSE, 
  method.args = list(start = c(a=10, b=0.01)))

Plot <- ggplot(df, aes(x=Time, y=Concentration)) + geom_point(size=2) + 
  geom_line(data=build,aes(x=x,y=y),color="blue") 

【讨论】:

    【解决方案2】:

    我认为这是不可能的。 (1) 我在ggplot_build(Plot) 生成的对象的内脏中四处寻找,没有发现任何可能的东西(这并不能证明它不存在,但是......)(2)如果您在ggpubr::stat_regline_equation() 函数的源代码中四处寻找,您可以see 而不是从平滑中寻找存储的信息,它必须调用package function that re-fits the linear model 以便它可以提取系数并构造方程。

    您可能只需要自己重新拟合模型:

    nls_fit <- nls(formula = Concentration ~ a*exp(-b *Time), 
                   start = c(a=10, b=0.01), data = df)
    coef(nls_fit)
    

    (您可能会发现broom::tidy(nls_fit) 返回的格式很方便。)

    对于这个特定的模型,您还可以通过

    获得系数
    cc <- coef(glm(Concentration ~ Time, data = df, family = gaussian(link= "log")))
    c(exp(cc[1]), -cc[2])
    

    原则上可以编写自己的 stat_ 函数镜像 stat_regline_equation 来封装此功能,但这将需要更多的工作/除非您这样做,否则不值得此操作非常常规或想让其他人轻松执行...

    【讨论】:

      猜你喜欢
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-05-05
      • 2015-12-10
      • 2012-07-21
      相关资源
      最近更新 更多