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

plt.bar绘制柱状图触发shape mismatch无法广播为单一形状错误

错误根因
  • 语法错误:绘图代码括号完全错位,plt.bar(y_train), y_test), color ='maroon')多写了2个多余的右括号,参数传递逻辑从写法上就不成立。
  • API用法错误:plt.bar()的核心参数规则是第一个参数传入柱子对应的x轴位置/类别,第二个参数传入对应柱子的高度,两个传入的序列长度必须完全一致。你直接把长度80000的y_train作为x参数、长度20000的y_test作为高度参数传入,两个数组长度差4倍,numpy无法完成形状广播匹配,就会抛出你看到的形状不匹配错误。
  • 绘图逻辑错误:你的需求是绘制训练集、测试集的标签分布柱状图,但原始y_train/y_test是逐样本的标签序列(每个元素对应一个样本的0/1标签),不是统计好的各标签样本计数,直接传入绘图接口完全不符合参数要求。
修复方案

先统计两个数据集的标签样本数,再调用bar接口绘图即可。

  1. 先做标签计数统计
import matplotlib.pyplot as plt

# 分别统计训练、测试集里0、1标签的样本量,按标签值升序排列保证顺序对应
train_cnt = y_train.value_counts().sort_index()
test_cnt = y_test.value_counts().sort_index()
  1. 根据需求选择绘图方式
  • 分组对比柱状图(推荐,直观对比两个数据集的分布差异)
plt.figure(figsize=(10, 5))
bar_width = 0.35
label_pos = [0, 1] # x轴两个位置分别对应负类、正类

# 绘制训练集柱子
plt.bar([pos - bar_width/2 for pos in label_pos], 
        train_cnt.values, 
        width=bar_width, 
        color='maroon', 
        label='训练集')
# 绘制测试集柱子
plt.bar([pos + bar_width/2 for pos in label_pos], 
        test_cnt.values, 
        width=bar_width, 
        color='navy', 
        label='测试集')

plt.xticks(label_pos, ['负类(Score≤2)', '正类(Score>3)'])
plt.ylabel('样本数量')
plt.title('训练/测试集标签分布对比')
plt.legend()
plt.show()
  • 分离子图展示
fig, (ax_train, ax_test) = plt.subplots(1, 2, figsize=(12, 5))

# 训练集子图
ax_train.bar(['负类', '正类'], train_cnt.values, color='maroon')
ax_train.set_title('训练集标签分布')
ax_train.set_ylabel('样本量')

# 测试集子图
ax_test.bar(['负类', '正类'], test_cnt.values, color='maroon')
ax_test.set_title('测试集标签分布')

plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 09:21:37