yearntolearn
yearntolearn

Reputation: 1074

superimpose a prediction curve on ggplot

I know this has been asked for multiple times, but I could not find an answer to solve the problem I am encountering.

I would like to generate a prediction curve and superimpose it on a ggplot. The model is a quadratic plateau nonlinear function.

Data as below

dd_ <- data.frame(yield = c(2.07, 1.58, 2.01, 2.27, 3.28,
                            2.31, 2.49, 2.41, 3.90, 3.26,
                            3.37, 3.83, 4.06, 3.54, 3.75,
                            3.48, 4.51, 3.39, 4.09, 3.87,
                            4.31, 4.36, 4.66, 3.79, 4.17, 
                            4.63, 3.99, 3.88, 4.73),
                  n_trt = c(0,0,0,0,25,25,25,25,
                            50,50,50,50,75,75,75,75,
                            100,100,100,100,125,125,125,125,
                            150,150,150,175,175))

the function is

quadratic.plateau <- function(alpha,beta,gamma, D, x){
  ifelse(x< D,alpha+beta*x+gamma*x*x,alpha+beta*D+gamma*D*D)
}

I use minpack.lm package as it creates a better fit than nls

library(minpack.lm)
library(ggiraphExtra)

q_model <- nlsLM(yield~quadratic.plateau(A,B,C, D, n_trt),
    data = dd_, start=list(A=2.005904,
                         B=0.03158664,
                         C=-0.0001082836, 
                         D = 145.8515 ))

ggPredict(q_model,interactive=TRUE,colorn=100,jitter=FALSE)

By doing this, I receive an error

Error: $ operator is invalid for atomic vectors

I also used

ggplot(dd_, aes(n_trt, yield)) +
geom_point(size = 0.5) +
geom_smooth(method = "quadratic.plateau", data = dd_)

but no prediction curve was generated.

I appreciate your help. Thanks!

Upvotes: 2

Views: 750

Answers (2)

yearntolearn
yearntolearn

Reputation: 1074

After a few attempts, this solves my problem.

eq1 = function(x){
ifelse(x< coef(q_model)[4], coef(q_model)[1]+coef(q_model)[2]*x+coef(q_model)[3]*x*x,
     coef(q_model)[1]+coef(q_model)[2]*coef(q_model)[4]+coef(q_model)[3]*coef(q_model)[4]*coef(q_model)[4])
}


ggplot(dd_, aes(n_trt, yield)) +
geom_point(size = 0.5) +
stat_function(fun=eq1,geom="line",color=scales::hue_pal()(2)[1])

enter image description here

Upvotes: 1

Ben Bolker
Ben Bolker

Reputation: 226731

Almost identical to this question: the main point is that you have to set se=FALSE because predict.nls() doesn't return standard errors ...

ggplot(dd_, aes(n_trt, yield)) +
  geom_point(size = 0.5) +
  geom_smooth(method="nlsLM",
              se=FALSE,
             formula=y~quadratic.plateau(A,B,C, D, x),
              method.args=list(start=list(A=2.005904,
                                          B=0.03158664,
                                          C=-0.0001082836, 
                                          D = 145.8515 )))

Upvotes: 2

Related Questions