Skip to content
Prev 77641 / 398502 Next

Add function to histogram?

Robert Lundqvist wrote:
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 - or a negative density except in the very 
latest physics).

Jim