emanuele
emanuele

Reputation: 2589

best fitting curve from plot in R

I have a probability density function in a plot called ph that i derived from two samples of data, by the help of a user of stackoverflow, in this way

 few <-read.table('outcome.dat',head=TRUE)
 many<-read.table('alldata.dat',head=TRUE)
 mh <- hist(many$G,breaks=seq(0,1.,by=0.03), plot=FALSE)
 fh <- hist(few$G, breaks=mh$breaks, plot=FALSE)
 ph <- fh
 ph$density <- fh$counts/(mh$counts+0.001)
 plot(ph,freq=FALSE,col="blue")

I would like to fit the best curve of the plot of ph, but i can't find a working method. how can i do this? I have to extract the vaule from ph and then works on they? or there is same function that works on

 plot(ph,freq=FALSE,col="blue")

directly?

Upvotes: 3

Views: 3208

Answers (2)

Tomas
Tomas

Reputation: 59565

Do you want a density function?

x = rnorm(1000)
hist(x, breaks = 30, freq = FALSE)
lines(density(x), col = "red")

Upvotes: 2

Carl Witthoft
Carl Witthoft

Reputation: 21532

Assuming you mean that you want to perform a curve fit to the data in ph, then something along the lines of nls(FUN, cbind(ph$counts, ph$mids),...) may work. You need to know what sort of function 'FUN' you think the histogram data should fit, e.g. normal distribution. Read the help file on nls() to learn how to set up starting "guess" values for the coefficients in FUN.

If you simply want to overlay a curve onto the histogram, then smoo<-spline(ph$mids,ph$counts); lines(smoo$x,smoo$y)

will come close to doing that. You may have to adjust the x and/or y scaling.

Upvotes: 3

Related Questions