You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言hist()函数分组区间问题:如何生成10个等距区间直方图

How to Get Exactly 10 Equal-Width Bins with R's 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:

  1. Calculate the range of your data:

    min_val <- min(dataset)
    max_val <- max(dataset)
    
  2. Generate 11 custom breakpoints (since 10 bins require 11 breakpoints):
    Use the seq() 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)
    
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:32:50