Janice Neumann
Janice Neumann

Reputation: 39

R and ggplot non-linear regression line

I'm trying to fit multiple non-linear regression lines and measured points into a plot and started like this:

ggplot(Sorption, aes(x=Ct, y=S, color=Depth)+
  geom_point()+
  geom_smooth(method = "nls", data = Sorption,
              se = FALSE,
              formula = 'S~Smax*K*Ct/1+K*Ct',
              method.args = list(start=c(K=2, Smax=1100, Ct=0.2, S=0.2)))

The formula in the code is the equation for a langmuir sorption isotherm and all the variables are given in the data=Sorption.

When I run this code, I get the following error:

**fitting parameters ‘K’, ‘Smax’, ‘Ct’, ‘S’ without any variables
Warning message:
Computation failed in `stat_smooth()`:
object 'S' not found** 

I have no idea what I'm doing right or wrong, so if anybody has a lead, I'd be forever grateful ;) I'm also not sure about the starting points and what to put in this last line of code. When I'm running this code I do get the actual measured points in the plot but no non-linear regression line.

Upvotes: 0

Views: 544

Answers (1)

langtang
langtang

Reputation: 24722

You can adjust the way you express formula, by using x and y directly

ggplot(Sorption, aes(x=Ct, y=S, color=Depth, group=Depth))+
  geom_point()+
  geom_smooth(method = "nls", se = FALSE,
              formula = y~Smax*K*x/1+K*x,
              method.args = list(start=c(K=2, Smax=1100)))

An example is with mtcars

ggplot(mtcars, aes(x=disp,y=mpg, color=as.factor(cyl), group=as.factor(cyl)))+
         geom_point() +
         geom_smooth(
           method = "nls", se = FALSE,
           formula = y~A*x^2 + B*x + C, 
           method.args=list(start=c(A=1, B=1, C=1))
        )

Output: mtcars_nls

Upvotes: 1

Related Questions