[R] Generating a vector for breaks in a histogram

Duncan Murdoch dmurdoch at pair.com
Thu Jul 3 16:19:56 CEST 2003

On Thu, 3 Jul 2003 14:48:04 +0100 , "michael watson (IAH-C)"
<michael.watson at bbsrc.ac.uk> wrote :

>Now this makes sense of course, my bins probably DON'T span the entire range of X.  SOOOOO I am still left with the same problem:
>1) two variables
>2) I want to draw histograms of both
>3) I want them to have the SAME x-y scale on the graph
>4) I want them to have the SAME bin range
>How do i do it?  Any suggestions?

I'd expand the range to cover both (otherwise your histogram will miss
some observations), but if you really want to do what you're asking,
use both xlim and breaks.  For example:

> x <- rnorm(100)

This gives the error you saw, because there are some negative values:

> hist(x, breaks=seq(0,5, len=6))
Error in hist.default(x, breaks = seq(0, 5, len = 6)) : 
        some `x' not counted; maybe `breaks' do not span range of `x'

But this works:

> hist(x, breaks=seq(-5,5, len=11),xlim=c(0,5))

It only shows the bins that are between 0 and 5, and a bit of the one
from -1 to 0.  If you don't even want that bit, then you could do a
histogram of a subset of your data:

> hist(x[x>0], breaks=seq(0,5,len=6))

You'll probably want to use ylim to force the vertical scales to match
between plots.

If none of these work, you should always be able construct the plot
you want using barplot(), where you do all the calculations for
positioning yourself.

Duncan Murdoch

More information about the R-help mailing list