Skip to content

Fitting arbitrary curve to 1D data with error bars

5 messages · Erkcan Özcan, Suzen, Mehmet

#
If you are after adding error bars in a scatter plot; one example is
given below :

#some example data
set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))

#calculate mean, min and max for each x-value
library(plyr)
df2 <- ddply(df,.(x),function(df)
c(mean=mean(df$y),min=min(df$y),max=max(df$y)))

#plot error bars
library(Hmisc)
with(df2,errbar(x,mean,max,min))
grid(nx=NA,ny=NULL)

(From: http://stackoverflow.com/questions/13032777/scatter-plot-with-error-bars)
#
Thanks, but if you have another closer look to my post, you will see that my question has nothing to do with drawing error bars on a plot.

What I want is to do a curve fit to a data with error bars.

Best,
e.
On 14 Nov 2013, at 04:21, Suzen, Mehmet wrote:

            
#
Maybe you are after "weights" option given by 'lm' or 'glm'

See: http://stackoverflow.com/questions/6375650/function-for-weighted-least-squares-estimates
On 14 November 2013 10:01, Erkcan ?zcan <erkcan at hotmail.com> wrote:
#
Thanks, this was a useful pointer. Since the function I am trying to fit is exponential, I decided to use nls. And I was able to reproduce exactly the results and the plot in the URL I had posted. For future reference, here is the R code I wrote:


require("gplots")
xx <- 1:10
yy <- c(1.56,1.20,1.10,0.74,0.57,0.55,0.31,0.27,0.28,0.11)
dy <- c(0.02,0.02,0.20,0.03,0.03,0.10,0.05,0.02,0.10,0.05)
plotCI(xx,yy,uiw=dy,gap=0)
nlmod <- nls(yy ~ Alpha * exp(Beta * xx), start=list(Alpha=1, Beta=-1))
lines(xx, predict(nlmod), col = "blue")
wnlmod <- nls(yy ~ Alpha * exp(Beta * xx), start=list(Alpha=1, Beta=-1), weights=dy^-2)
lines(xx, predict(wnlmod), col = "red")


Thanks to everybody who responded,

e.
On 14 Nov 2013, at 11:34, Suzen, Mehmet wrote: