在ggplot上叠加一条预测曲线

superimpose a prediction curve on ggplot

我知道这个问题已被多次询问,但我找不到解决我遇到的问题的答案。

我想生成一条预测曲线并将其叠加在 ggplot 上。该模型是二次平台非线性函数。

数据如下

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

函数是

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

我使用 minpack.lm 包,因为它比 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)

执行此操作时,我收到错误消息

Error: $ operator is invalid for atomic vectors

我也用过

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

但没有生成预测曲线。

感谢您的帮助。谢谢!

经过几次尝试,这解决了我的问题。

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

几乎与this question相同:重点是您必须设置se=FALSE因为predict.nls()没有return标准错误...

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