如何解决如何提取 stat_smooth 指数拟合参数 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,y=Concentration)) + geom_point(size=2) +
geom_line(data=build,aes(x=x,y=y),color="blue")
,
我认为这不可能。 (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
来封装此功能,但这样做会花费更多的工作/不值得除非你经常做这个操作,或者想让别人轻松做...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。