[R] fitting a histogram to a Gaussian curve

Vihan Pandey vihanpandey at gmail.com
Mon Mar 19 20:02:18 CET 2012


I'll check it out, thanks a million Micheal!

On 19 March 2012 19:59, R. Michael Weylandt <michael.weylandt at gmail.com> wrote:
> Take a look at fitdistr in the MASS package.
>
> fitdistr(x, "normal")
>
> I don't think you need to supply start values for the normal since its
> loglikelihood function is nicely behaved. You may need to for harder
> distributions.
>
> Michael
>
> On Mon, Mar 19, 2012 at 2:54 PM, Vihan Pandey <vihanpandey at gmail.com> wrote:
>> I see, that could be an option, however isn't there a fitting function
>> which would do that on given data?
>>
>> On 19 March 2012 19:49, R. Michael Weylandt <michael.weylandt at gmail.com> wrote:
>>> If I understand you correctly, a univariate Gaussian distribution is
>>> uniquely determined by its first two moments so you can just fit those
>>> directly (using sample mean for population mean and sample variance
>>> with Besel's correction for population variance) and get the "best"
>>> Gaussian (in a ML sense).
>>>
>>> E.g.,
>>>
>>> x <- rnorm(500, 3, 2)
>>>
>>> hist(x, freq = FALSE)
>>> lines(seq(min(x), max(x), length.out = 300) -> y, dnorm(y, mean(x),
>>> sd(x)), col = 2)
>>>
>>> Hope this helps,
>>> Michael
>>>
>>> On Mon, Mar 19, 2012 at 12:47 PM, Vihan Pandey <vihanpandey at gmail.com> wrote:
>>>> Hello,
>>>>
>>>> I am trying to fit my histogram to a smooth Gaussian curve(the data
>>>> closely resembles one except a few bars).
>>>>
>>>> This is my code :
>>>>
>>>> #!/usr/bin/Rscript
>>>>
>>>> out_file = "irc_20M_opencl_test.png"
>>>> png(out_file)
>>>>
>>>> scan("my.csv") -> myvals
>>>>
>>>> hist(myvals, breaks = 50, main = "My Distribution",xlab = "My Values")
>>>>
>>>> pdens <- density(myvals, na.rm=T)
>>>> plot(pdens, col="black", lwd=3, xlab="My values", main="Default KDE")
>>>>
>>>> dev.off()
>>>>
>>>> print(paste("Plot was saved in:", getwd()))
>>>>
>>>> the problem here is that I a jagged distribution, you can see the result :
>>>>
>>>> http://s15.postimage.org/9ucmkx3bf/foobar.png
>>>>
>>>> this is the original histogram :
>>>>
>>>> http://s12.postimage.org/e0lfp7d5p/foobar2.png
>>>>
>>>> any ideas on how I can smoothen it to a Gaussian curve?
>>>>
>>>> Thanks,
>>>>
>>>> - vihan
>>>>
>>>> ______________________________________________
>>>> R-help at r-project.org mailing list
>>>> https://stat.ethz.ch/mailman/listinfo/r-help
>>>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>>>> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list