简体   繁体   中英

R - fit a smooth curve through my data points

I wrote following script in 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)) . Is there a way I can achieve a 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.

I'm not sure what the purpose of your Amplitude and 'Flog 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.

#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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM