[R] Plotting frequency curve over histogram

(Ted Harding) Ted.Harding at manchester.ac.uk
Thu Dec 10 01:52:02 CET 2009


On 09-Dec-09 23:52:20, Gaurav Moghe wrote:
> Hello,
> This is a problem for which there seem to be several solutions online,
> but not really. My question was about plotting a curve over the
> histogram.
> All the previous posts and messages talk about generating a *density
> histogram* using (freq=F) and then plotting the density curve.
> However, I find that that seriously distorts my data and the plot
> becomes confounding to the viewer.
> 
> I was wondering if there's a way to do the following 2 things:
> 1) Plot both histogram and the overlying frequency curve in one plot
> 2) Plot multiple frequency curves in a single plot
> 
> I have been using the "hist" function for my job.
> 
> I'd appreciate if anyone could help me with the solution
> 
> Thanks,
> Gaurav

You presumably mean that the viewer expects to see a histogram of
counts, with the corresponding estimated curve of expected counts
for each bin-interval (NB *not* density!!) plotted over it.

The following is an example of how to achieve this.

  set.seed(54321)
  N <- 1000
  x <- rnorm(N)
  H <- hist(x,breaks=50)
  dx <- (H$breaks[2]-H$breaks[1])
  m  <- mean(x)
  s  <- sd(x)
  x0 <- H$breaks
  x1 <- c(x0[1]-dx/2,x0+dx/2)
  y0 <- H$counts
  lines(x1,N*dnorm((x1 - m)/s)*dx)

In the above, m and s are the estimated Mean and SD of the fitted
Normal distgribution. Therefore the estimated *density* at x is

  dnorm((x - m)/s)*dx

and a good approximation to the probability contained in a given
bin whose midpoint is at x1 is dnorm((x1 - m)/s)*dx, where dx is
the width of the bin. The total sample size being N, the expected
count for that bin is N*dnorm((x1 - m)/s)*dx.

With this explanation, the above should now be clear!

Ted.


--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 10-Dec-09                                       Time: 00:51:58
------------------------------ XFMail ------------------------------




More information about the R-help mailing list