[R] two histograms in the same graph

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Thu Jan 24 21:06:01 CET 2008

```Duncan Murdoch wrote:
> On 1/24/2008 9:43 AM, Juan Pablo Fededa wrote:
>
>> Dear Contributors:
>>
>> I have two vectors x and z, and I want to display the histograms of both
>> vectors in the same graph, x in red bars, z in blue bars.
>> If you have any clue on how to do that, I will be very glad to hear it!!!!!!
>>
>
> It's hard to design a graph like this that looks good, but it's easy to
>
> x <- rnorm(1000)
> y <- rnorm(1000, mean=1)
> breaks <- pretty(range(c(x,y)), 20)
> hist(x, breaks=breaks, col='red', main="Hist of x and y")
>
> Duncan Murdoch
>
This is where frequency polygons can be useful. The basically just play
connect-the-dots with the bar tops of the histogram, but since they are
transparent, they are more easily overplotted. They are quite a long way
towards density estimates, but retaining the feature of the histogram:
that it can be explained to the totally uninitiated, with no reference
to smoothing kernels and whatnot.

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)
plot(x, y, xlab=xlab, ylab= if (freq) "Frequency" else "Density",
type="o", pch=16, ...)
else
lines(x, y, type="o", pch=16, ...)
}
freqpoly(x,breaks=breaks)

(This is a bit of a rough sketch because "..." gets sent to incompatible
places)

--
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

```