I am trying to build and plot an nls model and having problems with defining starting values, and with plotting it on a graph on a log x-axis.
building the nls model:
a <- 5
b <- 2
c <- 3
x <- seq(1, 100, by = 1)
set.seed(123)
noise <- rnorm(length(X), mean = 0, sd = 0.1)
y <- a * x^(-b) + c + noise
df <- data.frame(x = x, y = y)
c.0 <- min(df$y) * 0.5
model.0 <- lm(log(y - c.0) ~ x, data=df)
start <- list(a=exp(coef(model.0)[1]), b=coef(model.0)[2], c=c.0)
nls_model <- nls(y ~ a * x^(b) + c, data = df, start= start)
putting in the start values by start = start
returns: Error… singular gradient.
putting in the actual start values by start= c(a=1.8095,b=-0.00155959,c=1.385)
returns: Error… Missing value or an infinity produced when evaluating the model.
With other datasets, exactly the same code did create an nls model succesfully. So I am trying to understand what produces the infinity value, and why doesn’t it work in some cases?
The second question is about plotting data in a model that could fit a model: Plotting other data with the x-axis on a linear scale creates this:
and with the x-axis on a logarithmic scale, it creates this:
The code that I used to plot these is as follows, but with another dataframe:
ggplot(df, aes(y=y,x=x))+
geom_point()+
geom_smooth(method = "nls", formula = y ~ a * x^(-b)+c, se = FALSE,
method.args = list(start= c(a=10,b=.1,c=.1)), color = 'red') +
theme_bw()+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
scale_x_continuous(breaks=c(1000,100,10,1))+
# coord_trans(x = "log10")+
annotate("text",x=1000,y=45, label = eq_label, parse = TRUE)+
labs(x="x",y="y")
So I am not sure, but I think it might be that the line in the logarithmic plot is actually true to the model, but because the power of the model itself is lower than the power of the axis transformation it seems like the slope is decreasing. However, is there still a way to create this line on a logarithmic x-axis in a way that is more presentable?