繁体   English   中英

如何提取 stat_smooth 指数拟合参数 ggplot2

[英]How to extract stat_smooth exponential fit parameters ggplot2

我已经尝试了这里找到的许多建议,但我根本无法弄清楚。

是否可以从拟合 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" ,但是当我添加指数函数时它不起作用。

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

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

您可以将其分配给对象: build <- 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") 

我不认为这是可能的。 (1) 我在ggplot_build(Plot)生成的对象的内脏中ggplot_build(Plot)寻找,但没有找到任何可能的东西(这并不能证明它不存在,但是......)(2)如果你在ggpubr::stat_regline_equation()函数的源代码您可以看到,与其从平滑中查看存储的信息,不如调用一个重新拟合线性模型包函数,以便它可以提取系数并构造方程.

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

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来封装此功能,但是除非您经常执行此操作或想让其他人轻松执行此操作,否则将需要做更多的工作/不值得...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM