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

R语言使用预定义分箱计算频数分布并绘制直方图

数值向量分箱统计结果

1. 基础信息

待处理的原始数值向量:[18, 20, 21, 22, 24, 26, 27, 34, 35, 35]
预定义的闭区间分箱规则:16-20、21-25、26-30、31-35

2. 频数&相对频数分布表

分箱区间频数相对频数
16-20220%
21-25330%
26-30220%
31-35330%
总计10100%

3. 直方图

文本版直方图(每个*代表1个观测值)

频数
4 |
3 |    ***        ***
2 |***      ***
1 |
0 +--------------------------------
    16-20  21-25  26-30  31-35
              分箱区间

运行代码可生成标准像素版直方图,效果和文本版一致,四个分箱的高度分别对应2、3、2、3的频数。

4. 可复用Python实现代码

import pandas as pd
import matplotlib.pyplot as plt

# 初始化参数
raw_data = [18, 20, 21, 22, 24, 26, 27, 34, 35, 35]
bin_edges = [15.5, 20.5, 25.5, 30.5, 35.5]
bin_labels = ["16-20", "21-25", "26-30", "31-35"]

# 分箱统计
cut_data = pd.cut(raw_data, bins=bin_edges, labels=bin_labels)
freq_result = cut_data.value_counts().sort_index()
rel_freq_result = (freq_result / len(raw_data) * 100).round(0).astype(int).astype(str) + "%"

# 打印统计表
stat_df = pd.DataFrame({
    "频数": freq_result,
    "相对频数": rel_freq_result
})
print(stat_df)

# 绘制直方图
plt.hist(raw_data, bins=bin_edges, edgecolor="black")
plt.xticks([(bin_edges[i] + bin_edges[i+1])/2 for i in range(len(bin_labels))], bin_labels)
plt.xlabel("分箱区间")
plt.ylabel("频数")
plt.title("数值分布直方图")
plt.show()

内容的提问来源于stack exchange,提问作者Adil Shalmanov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 22:51:03