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

Matplotlib制作并排直方图和折线图动画时AttributeError报错解决

问题原因

你触发报错的核心原因是FuncAnimation开启blit=True模式时,要求动画函数返回扁平化的所有需要更新的Artist对象序列,但你当前animate函数的返回值是bar_container.patches, line,其中bar_container.patches本身就是一个包含所有直方图矩形的列表,相当于你返回了[矩形对象列表, 折线对象]这种嵌套结构,Matplotlib遍历更新的时候拿到了内层的列表,尝试调用get_zorder()方法就会报错,因为列表根本没有这个属性。

修复方案

只需要修改animate函数的返回值,把两个部分的对象展开合并成一个一维序列即可,两种修改方式都可以正常运行:

  1. 用解包语法把patches列表展开,和line合并成元组返回
  2. 把patches列表和line放在同一个列表里返回

需修改的代码片段

原返回行:

return bar_container.patches, line

替换为:

return *bar_container.patches, line

或

return bar_container.patches + [line]

完整可运行代码

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

n_frames = 100 #total number of frames
time = [] #x-axis data
mean = [] #y-axis data

def animate(frame_number, bar_container, line):
        data = np.random.randn(1000) #generate data

        n, _ = np.histogram(data, HIST_BINS) #create histogram

        for count, rect in zip(n, bar_container.patches):
            rect.set_height(count)

        time.append(frame_number)#update x-axis
        mean.append(np.mean(data))#update y-axis

        line.set_data(time, mean)

        # 修改了返回值结构
        return *bar_container.patches, line

HIST_BINS = np.linspace(-4, 4, 100)
data = np.random.randn(1000)
n, _ = np.histogram(data, HIST_BINS)

fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.set_ylim(top=55)  # set safe limit to ensure that all data is visible.
ax1.set_ylabel('Count')
ax1.set_xlabel('Lengths')

_, _, bar_container = ax1.hist(data, HIST_BINS, lw=1, ec="yellow", fc="green", alpha=0.5)

line, = ax2.plot([], [])
ax2.set_ylim(-4,4)
ax2.set_xlim(0, n_frames)
ax2.set_ylabel('mean')
ax2.set_xlabel('time')

fig.tight_layout(pad = 1)

ani = animation.FuncAnimation(fig, animate, frames = np.arange(n_frames), fargs = (bar_container,line), blit=True)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:06:07