R - 通过我的数据点拟合平滑曲线

时间:2015-03-15 15:12:24

标签: r plot curve-fitting

我在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)),   
     )

我想要拟合的曲线是1/(sqrt(1+x^2))种类。有没有办法实现smooth fit

1 个答案:

答案 0 :(得分:1)

您需要使用R中的nls()函数。它旨在处理data.frame中的变量,因此您需要创建一个数据框来包含FA个变量。

我不确定您的Amplitude和&#39; Flog variables are; in this example I assumed you wanted to predict A values from F`的目的是什么用你的等式。

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

该代码生成以下图表:

enter image description here