You need to enable JavaScript to run this app. 绘制每组3个的柱状图时报ValueError:对象无法广播为单一形状
优惠活动
大模型
产品
解决方案
定价
更多

绘制每组3个的柱状图时报ValueError:对象无法广播为单一形状

错误原因与修复方案

核心报错原因

你触发ValueError: Objects cannot be broadcast to a single shape的核心原因是横坐标长度与数据长度不匹配:
你定义k = 10,生成的index = np.arange(k)是包含10个元素的数组,而你提供的averaged precision、recall、fscore三个指标的列表长度均为9,二者形状不一致无法对齐绘图。

其他代码问题梳理

  • 柱子宽度设置不合理:当前barwidth = 0.4,三个柱子总宽度为1.2,超过了默认每组间隔的1个单位,会导致相邻组柱子重叠
  • 坐标轴、标题设置方法错误:Axes对象没有xlabel/ylabel/title方法,需要用set_xlabel/set_ylabel/set_title
  • 图例传参错误:ax.legend()第一个参数需要传入所有柱子对象的列表,不能拆分传参
  • 方法拼写与精度问题:自定义函数中get_heightd()是拼写错误,应为get_height();用%d格式化会丢失小数精度,不适合得分类指标展示

修正后完整代码

import numpy as np
import matplotlib.pyplot as plt

# 指标数据
precisionKlist = [0.3408782254413762, 0.4431790795129584, 0.44562855758681447, 0.6930575070252911, 0.7048203106429318, 0.7076336331481228, 0.5817814329884687, 0.5915420288865595, 0.7056966148161392]
recallKlist = [1.0, 0.39345726247142776, 0.18316722513975484, 0.36019465995952776, 0.047896671507928194, 0.10484171589149509, 0.04886434702343402, 0.08009139022931534, 0.2240637724379194]
fscoreKlist = [0.5084402430790007, 0.41684067176950357, 0.259621799568279, 0.47402819742590835, 0.08969784843837761, 0.18262590836627177, 0.0901563785388454, 0.14108119734411395, 0.3401328941951721]

barwidth = 0.25
# 直接取数据实际长度作为k值,避免手动设置不匹配
k = len(precisionKlist)

fig = plt.figure()
index = np.arange(k)
ax = fig.add_subplot(111)

rect1 = ax.bar(index, precisionKlist, barwidth, color='b', align = 'center', label='precision')
rect2 = ax.bar(index + barwidth, recallKlist, barwidth, color='g', align = 'center', label='recall')
rect3 = ax.bar(index + 2*barwidth, fscoreKlist, barwidth, color='r', align = 'center', label='fscore')

# 修正坐标轴与标题设置方法
ax.set_xlabel("k values")
ax.set_ylabel("BcubedScore")
ax.set_title("Bcubed Scores for UnNormalized Data of KMedian")
ax.legend()

def autolabel(rects):
    for rect in rects:
        # 修正方法拼写
        h = rect.get_height()
        # 调整格式化规则,保留两位小数适配得分指标
        ax.text(rect.get_x() + rect.get_width()/2., 1.01*h, '%.2f'%h, ha='center', va='bottom')
      
autolabel(rect1)
autolabel(rect2)
autolabel(rect3)
# 调整x轴刻度位置到每组柱子中间,提升可读性
ax.set_xticks(index + barwidth)
ax.set_xticklabels(range(1, k+1))
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 06:45:01