R语言hist()函数分组区间问题:如何生成10个等距区间直方图
hist() Function Hey there! I totally get the frustration here—R's hist() function behaves a bit unexpectedly when you pass a number to the breaks argument. Let me clear this up for you:
Why breaks = 10 gave you 12 bins
When you use breaks = 10, you're not telling R to create exactly 10 bins. Instead, you're giving it a suggestion for the number of bins. R will automatically adjust the breakpoints to what it considers "nice" (round, easy-to-read values), which can result in a different number of bins than you requested. This is why you ended up with 12 instead of 10.
The fix: Custom equal-width breakpoints
To force exactly 10 equal-width intervals, you need to calculate the breakpoints manually instead of relying on R's automatic adjustment. Here's how to do it step by step:
Calculate the range of your data:
min_val <- min(dataset) max_val <- max(dataset)Generate 11 custom breakpoints (since 10 bins require 11 breakpoints):
Use theseq()function to create equally spaced values from the minimum to maximum of your data, with exactly 11 points:custom_breaks <- seq(min_val, max_val, length.out = 11)Pass the custom breaks to
hist():
Now use these breakpoints in your histogram call:hist(dataset, breaks = custom_breaks)
Optional: Make breakpoints "nicer" (still equal-width)
If you want your breakpoints to be round numbers instead of exact min/max values (for readability), you can adjust the min and max to the nearest whole number first:
min_val <- floor(min(dataset)) # Round down to nearest integer max_val <- ceiling(max(dataset)) # Round up to nearest integer custom_breaks <- seq(min_val, max_val, length.out = 11) hist(dataset, breaks = custom_breaks)
This will still give you 10 equal-width bins, but with cleaner-looking interval endpoints.
Example to test
Let's say your dataset has a minimum of 12.3 and maximum of 87.1. The code above would generate breakpoints at 12.3, 19.78, 27.26, ..., 87.1—exactly 10 equal-width intervals between those values.
内容的提问来源于stack exchange,提问作者Bobby

