[英]R - fit a smooth curve through my data points
I wrote following script in R
: 我在R
编写了以下脚本:
F<-c(1.485, 1.052, .891, .738, .623, .465, .343, .184, .118, .078, 1.80,
2.12, 2.31, 2.83, 3.14, 3.38, 7.70, 15.35, 20.72, 22.93)
A<-c(4.2, 4.8, 5.0, 5.2, 5.3, 5.5, 5.6, 5.7, 5.8, 5.9, 3.8, 3.5, 3.4, 2.9,
2.7, 2.5, 1.2, 0.6, 0.5, 0.5)
Amplitude <- A/2
Flog <- log(F)
plot(Flog, Amplitude, type="p", lwd=1,
xlab=expression(paste(frequency,' ', log[e](Hz/s^-1))),
ylab=expression(paste(amplitude,' ', U/V)),
)
The curve I want to fit is of the kind 1/(sqrt(1+x^2))
. 我要拟合的曲线属于1/(sqrt(1+x^2))
。 Is there a way I can achieve a smooth fit
? 有什么方法可以使我变得smooth fit
吗?
You need to use the nls()
function in R. It is designed to work on variables in a data.frame
, so you will need to make a data frame to contain your F
and A
variables. 您需要在R中使用nls()
函数。该函数旨在处理data.frame
变量,因此您需要制作一个数据框以包含F
和A
变量。
I'm not sure what the purpose of your Amplitude
and 'Flog variables are; in this example I assumed you wanted to predict
我不确定您的Amplitude
和'Flog variables are; in this example I assumed you wanted to predict
的用途是什么variables are; in this example I assumed you wanted to predict
variables are; in this example I assumed you wanted to predict
A values from
F` values using your equation. variables are; in this example I assumed you wanted to predict
使用公式values from
F`值variables are; in this example I assumed you wanted to predict
A values from
。
#define data
F<-c(1.485, 1.052, .891, .738, .623, .465, .343, .184, .118, .078, 1.80,
2.12, 2.31, 2.83, 3.14, 3.38, 7.70, 15.35, 20.72, 22.93)
A<-c(4.2, 4.8, 5.0, 5.2, 5.3, 5.5, 5.6, 5.7, 5.8, 5.9, 3.8, 3.5, 3.4, 2.9,
2.7, 2.5, 1.2, 0.6, 0.5, 0.5)
#put data in data frame
df = data.frame(F=F, A=A)
#fit model
fit <- nls(A~k1/sqrt(k2 + F^2)+k3, data = df, start = list(k1=6,k2=1,k3=0))
summary(fit)
Formula: A ~ k1/sqrt(k2 + F^2) + k3
Parameters:
Estimate Std. Error t value Pr(>|t|)
k1 9.09100 0.17802 51.067 < 2e-16 ***
k2 2.55225 0.08465 30.150 3.36e-16 ***
k3 0.06881 0.03787 1.817 0.0869 .
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Residual standard error: 0.05793 on 17 degrees of freedom
Number of iterations to convergence: 6
Achieved convergence tolerance: 9.062e-07
#plot results
require(ggplot2)
quartz(height=3, width=3)
ggplot(df) + geom_point(aes(y=A, x=F), size=3) + geom_line(data=data.frame(spline(df$F, predict(fit, df$A))), aes(x,y), color = 'red')
quartz.save('StackOverflow_29062205.png', type='png')
That code produces the following graph: 该代码产生下图:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.