Re: [R] superimpose density line over hist

From: Ted Harding <Ted.Harding_at_nessie.mcc.ac.uk>
Date: Wed 14 Dec 2005 - 02:50:24 EST


On 13-Dec-05 Albert Vilella wrote:
> Hi all,
>
> I'm trying to superimpose a rchisq density line over a histogram with
> something like:
>
> hist(alnlength)
> lines(density(rchisq(length(alnlength), 4)),col="red")
>
> But the rchisq line won't appear anywhere,
>
> Anyone knows what I am missing here?

Well, it's certainly somewhere, but not within the window of your graphic!

What you're missing is

  1. Breaks in 'hist'
  2. Allowing for (1) the widths of the bins, (2) the size of the sample, when you drawn the curve.

Example (this should work most of the time, but if it doesn't because you have a sample that goes out of range just try again):

  alnlength<-rchisq(1000,4)
  x<-0.25*(0:100)
  hist(alnlength,breaks=0.25*(0:100))
  lines(x,1000*dchisq(x,4)*0.25)

Note that to get the 'lines' matching the histogram you have to a) multiply the density by the binswidth to get probabilities; b) multiply by the sample size so that the vertical scale of

   the curve matches that of the histogram (which here is showing    counts).

If you don't want to set the breakpoints explicitly but leave it to 'hist', you can subsequently extract the breakpoints from the 'hist' object and carry on from there.

Hoping this helps,
Ted.



E-Mail: (Ted Harding) <Ted.Harding@nessie.mcc.ac.uk> Fax-to-email: +44 (0)870 094 0861
Date: 13-Dec-05                                       Time: 15:50:21
------------------------------ XFMail ------------------------------

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Wed Dec 14 03:17:20 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:41:36 EST