XEZ
XEZ

Reputation: 11

Non linear model plotting issues using ggplot

I have a problem plotting an NLS-fit via stat_smooth. Interestingly, the curve of the fit is shifted in the negative y direction. Does anyone know what could be the reason for this? Below is the code, data and a sample graph (URL):

y<-c(0.686, 0.674, 0.631, 0.580, 0.520, 0.440, 0.411, 0.401, 0.338, 0.262, 0.218, 0.703, 0.628,0.584, 0.547, 0.513, 0.457, 0.395, 0.372, 0.326, 0.255, 0.213, 0.760, 0.684, 0.622, 0.577, 0.550, 0.463, 0.395, 0.352, 0.311, 0.244, 0.212)
x<-c(0.03,  0.08,  0.15,  0.23,  0.30,  0.75,  1.50,  2.25,  3.01,  7.52, 15.03,  0.03,  0.08, 0.15,  0.23,  0.30,  0.75,  1.50,  2.25,  3.01,  7.52, 15.03,  0.03,  0.08,  0.15,  0.23,0.30,  0.75,  1.50,  2.25,  3.01,  7.52, 15.03)  
df<-as.data.frame(cbind(x,y)) 
ggplot(df,aes(x=x,y=y))+
  geom_point()+
  stat_smooth(method = "nls", formula = log10(y) ~ c1*log10(x)+c2,
              method.args=list(start=list(c1=-0.2,c2=-0.4)),
              se=FALSE)

enter image description here

Many thanks XEZ

Upvotes: 1

Views: 84

Answers (1)

teunbrand
teunbrand

Reputation: 38023

Like stefan mentioned in the comments, it's because you're fitting log10(y). One solution other that transforming the input values, is to inverse the log transformation after the fit has been calculated. You can do this by using the stage() function:

library(ggplot2)

y<-c(0.686, 0.674, 0.631, 0.580, 0.520, 0.440, 0.411, 0.401, 0.338, 0.262, 0.218, 0.703, 0.628,0.584, 0.547, 0.513, 0.457, 0.395, 0.372, 0.326, 0.255, 0.213, 0.760, 0.684, 0.622, 0.577, 0.550, 0.463, 0.395, 0.352, 0.311, 0.244, 0.212)
x<-c(0.03,  0.08,  0.15,  0.23,  0.30,  0.75,  1.50,  2.25,  3.01,  7.52, 15.03,  0.03,  0.08, 0.15,  0.23,  0.30,  0.75,  1.50,  2.25,  3.01,  7.52, 15.03,  0.03,  0.08,  0.15,  0.23,0.30,  0.75,  1.50,  2.25,  3.01,  7.52, 15.03)  
df<-as.data.frame(cbind(x,y)) 
ggplot(df,aes(x=x,y=y))+
  geom_point()+
  stat_smooth(method = "nls", formula = log10(y) ~ c1*log10(x)+c2,
              method.args=list(start=list(c1=-0.2,c2=-0.4)),
              aes(y = stage(y, after_stat = 10^y)),
              se=FALSE)

Created on 2021-06-29 by the reprex package (v1.0.0)

Upvotes: 1

Related Questions