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

使用Matplotlib可视化my_data数据集GRADE列出现空白子图求助

解决Matplotlib绘制GRADE分布时出现空白子图的问题

嘿,我来帮你搞定这个空白图的问题!你的代码核心问题是Matplotlib的bar()方法参数使用不正确,导致它不知道该用什么数据来绘制柱子。咱们一步步来排查和修复:

问题根源

你写的ax.bar('GRADE', align='center', data=my_data)只指定了data参数和一个列名,但bar()函数需要明确知道x轴的类别(GRADE的取值)和每个类别对应的高度(计数)。只传一个列名的话,Matplotlib无法识别你要表达的逻辑,自然就画不出任何内容了。

解决方案

首先要确保你有「GRADE类别」和「对应计数」的结构化数据,然后正确调用bar()方法:

步骤1:准备正确的绘图数据

分两种情况处理:

  • 如果你的my_data是原始数据集(每行对应一个样本的GRADE):
    先统计每个GRADE的出现频次:
    import pandas as pd
    # 统计频次并转为DataFrame
    grade_counts = my_data['GRADE'].value_counts().reset_index()
    grade_counts.columns = ['GRADE', 'Count']  # 重命名列,方便后续调用
    
  • 如果你的my_data已经是汇总好的(包含GRADE和Count两列):
    直接用这个数据集就行,不用额外处理。

步骤2:修改绘图代码

明确指定bar()的x和height参数,结合data参数来关联列名:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(xlabel="Grade", ylabel="Count", title="Grade Distribution")
# 关键:指定x轴用GRADE列,高度用Count列
ax.bar(x='GRADE', height='Count', align='center', data=grade_counts)
# (可选)给每个柱子添加数值标签,让图表更直观
for p in ax.patches:
    ax.annotate(str(p.get_height()), 
                (p.get_x() + p.get_width()/2., p.get_height()),
                ha='center', va='center', 
                xytext=(0, 5), textcoords='offset points')
plt.show()

完整可运行示例

如果你想快速验证,可以用这段模拟你给出的计数的代码:

import matplotlib.pyplot as plt
import pandas as pd

# 模拟你的数据:GRADE和对应计数
data = {
    'GRADE': ['A', 'B', 'G', 'P', 'C'],
    'Count': [38616, 658, 16041, 7590, 33]
}
my_data = pd.DataFrame(data)

fig, ax = plt.subplots()
ax.set(xlabel="Grade", ylabel="Count", title="Grade Distribution")
ax.bar(x='GRADE', height='Count', align='center', data=my_data)
# 添加数值标签
for p in ax.patches:
    ax.annotate(str(p.get_height()), 
                (p.get_x() + p.get_width()/2., p.get_height()),
                ha='center', va='center', 
                xytext=(0, 5), textcoords='offset points')
plt.show()

运行这段代码后,你就能看到正常显示的GRADE分布柱状图啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:59:46