4

I need to plot a vector of numbers. Let's say these numbers range from 0 to 1000. I need to make a histogram where the x axis goes from 100 to 500, and I want to specify the number of bins to be 10. How do I do this?

I know how to use xlim and break separately, but I don't know how to make a given number of bins inside the custom range.

user3394040
  • 947
  • 13
  • 22
  • Can you please provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? – ccapizzano Jun 26 '14 at 00:41

1 Answers1

3

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

Tomas
  • 57,621
  • 49
  • 238
  • 373