[R] hist overlay...

Ross Ihaka ihaka at stat.auckland.ac.nz
Wed Mar 26 21:26:46 CET 2003


Vasudevan, Geetha wrote:
> thanks to all for the 2d scatter plot.
> 
> i have one more. 
> 
> how do i plot 'hist(y1, col="red") and hist(y2,col="blue") in the same window? 

Here are a couple of ways to do what you have asked for
(as oppposed to want you want :-).

I'm assuming that you precompute the histograms as follows:

x <- rnorm(100)
y <- rnorm(100)
xh = hist(x, plot=FALSE)
yh = hist(y, plot=FALSE)

You can customize these two "hist" calls anyway you like.

Here is a function which will plot the result as superimposed bars.

hist2v <-
function(xh, yh) {
   plot.new()
   plot.window(xlim=range(xh$breaks, yh$breaks),
               ylim=range(0, xh$density, yh$density))
   rect(xh$breaks[-length(xh$breaks)], 0,
        xh$breaks[-1], xh$density, border="blue")
   rect(yh$breaks[-length(yh$breaks)], 0,
        yh$breaks[-1], yh$density, border="red")
   axis(1)
   axis(2)
}

and one which will plot only the tops of the bars:

hist2v <-
function(xh, yh) {
   plot.new()
   plot.window(xlim=range(xh$breaks, yh$breaks),
               ylim=range(0, xh$density, yh$density))
   nx = length(xh$density)
   ny = length(yh$density)
   lines(rep(xh$breaks, c(1, rep(2, nx - 1), 1)),
         rep(xh$density, each = 2), col = "red")
   lines(rep(yh$breaks, c(1, rep(2, ny - 1), 1)),
         rep(yh$density, each = 2), col = "blue")
   axis(1)
   axis(2)
}

Either of these functions could be called as

hist2v(xh, yh)

It would be easy to add colour and line texture arguments.

-- 
Ross Ihaka                         Email:  ihaka at stat.auckland.ac.nz
Department of Statistics           Phone:  (64-9) 373-7599 x 85054
University of Auckland             Fax:    (64-9) 373-7018
Private Bag 92019, Auckland
New Zealand



More information about the R-help mailing list