This is a very good question actually! I was bothered by this all the time but finally your question has kicked me to finally solve it :-)
Well, in this case we cannot simply do hist(x, xlim = c(100, 500), breaks = 9)
, as the breaks
refer to the whole range of x, not related to xlim
(in other words, xlim
is used only for plotting, not for computing the histogram and setting the actual breaks). This is a clear flaw of the hist
function and there is no simple remedy found in the documentation.
I think the easiest way out is to "xlim" the values before they go to the hist
function:
x <- runif(1000, 0, 1000) # example data
hist(x[x > 100 & x < 500], breaks = 9)
breaks
should be number of cells minus one.
For more info see ?hist