简体   繁体   中英

How to extract stat_smooth exponential fit parameters ggplot2

I've already tried many of the suggestions found here, but I simply can't figure it out.

Is it possible to extract the equation (y = a+exp(-b*x)) from a line fitted with stat_smooth?

This is a data example:

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]))

在此处输入图片说明

I tried to use "stat_regline_equation" , but it does not work when I add the exponential function.

To extract data from ggplot you can use: ggplot_build()

Values from stat_smooth() are in ggplot_build(Plot)$data[[2]]

You can assign it to the object: build <- ggplot_build(Plot)$data[[2]]

Both codes below give the same result

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)))

and

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

I don't think it's possible. (1) I poked around in the guts of the object generated by ggplot_build(Plot) and didn't find anything likely (that doesn't prove it isn't there but...) (2) If you poke around in the source code of the ggpubr::stat_regline_equation() function you can see that rather than poke around in the stored information from the smooth it has to call a package function that re-fits the linear model so it can extract the coefficients and construct the equation.

You probably just have to re-fit the model yourself:

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

(You might find the format returned by broom::tidy(nls_fit) convenient.)

For this particular model you can also get the coefficients via

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

You could in principle write your own stat_ function mirroring stat_regline_equation that would encapsulate this functionality, but it would be a lot more work/wouldn't be worth it unless you were doing this operation very routinely or wanted to make it easy for others to do ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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