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

如何为两个numpy数组生成的matplotlib柱状图添加标注并解决报错?

你使用numpy数组作为数据源不会增加柱状图标注的实现难度,本次报错和数据源类型无关。

报错原因

plt.bar()执行后返回的是BarContainer类型对象,该对象没有annotate属性,annotate是matplotlib.pyplot模块的原生方法,调整调用对象即可解决问题。

修复后的完整代码

import matplotlib.pyplot as plt
import numpy as np

# 原始数据
x = np.array([' A6', ' Q2', ' Q5', ' A5', ' A1', ' A4', ' Q3', ' A3'])
y = np.array([748, 822, 877, 882, 1347, 1381, 1417, 1929])

plt.figure()
plot = plt.bar(x, y)
# 仅将原代码的plot.annotate改为plt.annotate即可
for bar in plot.patches:
    plt.annotate(bar.get_height(),
                  (bar.get_x() + bar.get_width() / 2,
                   bar.get_height()), ha='center', va='center',
                  size=15, xytext=(0, 8),
                  textcoords='offset points')
plt.xlabel("Car Model")
plt.ylabel("Car Frequency")
plt.title("Frequency of Most Popular Audi Cars")
plt.ylim(bottom=0, top=2100) # 调整y轴上限,避免最高柱的标注超出画布显示范围
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:27:00