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

如何基于DataFrame生成成绩频率分布、累计频率并绘制可视化图表

成绩频率分布计算与可视化实现方案

1. 依赖库导入

基于pandas做数据统计,matplotlib做可视化,先导入相关依赖:

import pandas as pd
import matplotlib.pyplot as plt

2. 频率与累计频率计算

首先将存储为宽表的成绩数据转换为长表,再统计频率、累计频率:

# 替换为你自己的实际成绩DataFrame
# 此处为示例数据:行是学生,列是课程,值为1-10分的成绩
df = pd.DataFrame(
    data = [[7,6,8,5,9,6], [5,7,4,8,6,9], [8,9,7,6,7,5], [6,5,9,7,4,8]],
    index = ['a','b','c','d'],
    columns = ['C1','C2','C3','C4','C5','C6']
)

# 提取所有课程的所有成绩到一维序列
all_scores = df.melt(value_name='score')['score']

# 统计频率,补全1-10分的所有分数段(无成绩的分数段频率为0)
freq_result = all_scores.value_counts(normalize=True, sort=False).reindex(range(1,11), fill_value=0).sort_index().reset_index()
freq_result.columns = ['score', 'frequency']
# 计算累计频率
freq_result['cumulative_frequency'] = freq_result['frequency'].cumsum()

# 如需转百分比格式直接查看,可执行以下代码
freq_result[['frequency', 'cumulative_frequency']] = (freq_result[['frequency', 'cumulative_frequency']] * 100).round(2).astype(str) + '%'

# 输出统计结果
print(freq_result)

3. 可视化绘制

支持同时输出频率柱状图和累计频率折线图,双轴展示更直观:

# 先拿到数值型的统计结果用于绘图
plot_data = all_scores.value_counts(normalize=True, sort=False).reindex(range(1,11), fill_value=0).sort_index().reset_index()
plot_data.columns = ['score', 'frequency']
plot_data['cumulative_frequency'] = plot_data['frequency'].cumsum()

# 创建画布与双轴
fig, ax1 = plt.subplots(figsize=(10, 6))

# 左侧Y轴:频率柱状图
ax1.bar(plot_data['score'], plot_data['frequency'], color='#4a90e2', alpha=0.7, label='频率')
ax1.set_xlabel('成绩(分值范围1-10)')
ax1.set_ylabel('频率', color='#4a90e2')
ax1.tick_params(axis='y', labelcolor='#4a90e2')
ax1.set_xticks(range(1, 11))

# 右侧Y轴:累计频率折线图
ax2 = ax1.twinx()
ax2.plot(plot_data['score'], plot_data['cumulative_frequency'], color='#f5a623', marker='o', linewidth=2, label='累计频率')
ax2.set_ylabel('累计频率', color='#f5a623')
ax2.tick_params(axis='y', labelcolor='#f5a623')

# 添加图例与标题
fig.legend(loc="upper right", bbox_to_anchor=(0.9, 0.9))
plt.title('成绩频率分布及累计频率统计')
plt.show()

补充说明

  • 统计结果中frequency列为对应分数在所有成绩中的占比,cumulative_frequency为小于等于当前分数的成绩累计占比
  • 代码中已经处理了无成绩的分数段,会自动补全0值,保证1-10分所有分值都有对应统计结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:39:04