Re: [R] Add function to histogram?

From: Jim Lemon <bitwrit_at_ozemail.com.au>
Date: Thu 22 Sep 2005 - 05:27:36 EST

Robert Lundqvist wrote:
> Is there any neat way to add a curve (frequency function or the like) to a
> histogram or other plots? I haven't found one yet...
>
For a general solution, one usually has to scale the density function to fit the plot. The simple, but convenient, function rescale() in the plotrix package can be used like this:

add.density.curve<-function(y,density=NA) {   xyrange<-par("usr")
  if(is.na(density)) y.density<-density(y)   lines(seq(xyrange[1],xyrange[2],length=length(y.density$y)),    rescale(y.density$y,c(0,xyrange[4]))) }

This only works for histograms, but I am working on a general function that will outsmart the habit of some functions of running the plot range into negative numbers when these are not possible (i.e. you can't have a negative count in a histogram -