如何从R中的nls获取图? [英] How get plot from nls in R?

查看:288
本文介绍了如何从R中的nls获取图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中,我使用nls进行非线性最小二乘拟合.然后,如何使用拟合提供的系数值来绘制模型函数?

In R I use nls to do a nonlinear least-squares fit. How then do I plot the model function using the values of the coefficients that the fit provided?

(是的,这是来自R相对新手的非常天真问题.)

(Yes, this is a very naive question from an R relative newbie.)

推荐答案

使用?nls中的第一个示例,并按照该示例我逐行指出,可以实现以下目的:

Using the first example from ?nls and following the example I pointed you to line by line achieves the following:

#This is just our data frame
DNase1 <- subset(DNase, Run == 1)
DNase1$lconc <- log(DNase1$conc)
#Fit the model
fm1DNase1 <- nls(density ~ SSlogis(lconc, Asym, xmid, scal), DNase1)

#Plot the original points
# first argument is the x values, second is the y values
plot(DNase1$lconc,DNase1$density)

#This adds to the already created plot a line
# once again, first argument is x values, second is y values
lines(DNase1$lconc,predict(fm1DNase1))

用于nls参数的predict方法将自动返回拟合的y值.或者,您添加一个步骤并执行

The predict method for a nls argument is automatically returning the fitted y values. Alternatively, you add a step and do

yFitted <- predict(fm1DNase1)

,然后在第二个参数中将yFitted传递给lines.结果看起来像这样:

and pass yFitted in the second argument to lines instead. The result looks like this:

或者,如果您想要平滑的"曲线,您要做的就是简单地重复此过程,但是在更多点上评估函数:

Or if you want a "smooth" curve, what you do is to simply repeat this but evaluate the function at more points:

r <- range(DNase1$lconc)
xNew <- seq(r[1],r[2],length.out = 200)
yNew <- predict(fm1DNase1,list(lconc = xNew))

plot(DNase1$lconc,DNase1$density)
lines(xNew,yNew)

这篇关于如何从R中的nls获取图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆