[R] how to draw histograms on multiple variables in a graph?

Peter Dalgaard p.dalgaard at biostat.ku.dk
Fri Oct 27 13:56:01 CEST 2006


"Hu Chen" <chencheva at gmail.com> writes:

> for example, I have two sets, x and y.
> I want to draw their histograms using different colors in a graph.
> I didn't find how to do this by reading ?hist
> Thanks very much.

You can't do that because it looks horrible ;-)

Actually, you can, because plot.histogram understands add=TRUE.

However, the opaque blocks of histograms tend to obscure eachother, so
you'd rather have something like back-to-back displays (which do
exist, I believe, in some package, but I've forgotten where).

You might do it with frequency polygons (which pretty much just amount
to playing "connect the dots" with histograms). Here's a bit of code
that I had lying about; overplotting is possible by add=TRUE -- you
likely need to manually adjust the xlim and ylim, though.

freqpoly <- function(x, ..., xlab=deparse(substitute(x)), add=FALSE,
    freq=FALSE) {
    force(xlab)
    h <- hist(x, ..., plot=FALSE)
    nbin <- length(h$mids)
    minb <- h$breaks[1]
    maxb <- h$breaks[nbin+1]
    minm <- h$mid[1]
    maxm <- h$mid[nbin]
    xmin <- minb - (minm - minb)
    xmax <- maxb + (maxb - maxm)
    x <- c(xmin,h$mid,xmax)
    y <- c(0, if (freq) h$counts else h$density, 0)
    if (!add)
        plot(x, y, xlab=xlab, ylab= if (freq) "Frequency" else "Density",
             type="o", pch=16, ...)
    else
        lines(x, y, type="o", pch=16, ...)
}


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list