首页 > 解决方案 > Matplotlib 在子图中为多个条形图设置动画

问题描述

我已经使用 FuncAnimation 成功地为单个条形图制作了动画,但我现在希望在子图中同时有 3 个条形图。我不知道我的动画函数应该返回什么。我试图为一个条形图调整我的代码以使其适用于 3。这是我的尝试,但我收到一条错误消息,提示“AttributeError:'BarContainer' 对象没有属性'get_zorder'”。我的数据“soln”是一个 3x1000x10 的列表。3 用于每个子图,10 用于每个条。

我相信这是一个最小的例子。 在此处输入图像描述


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

soln = np.array([[[1, 0, 0],[1,1,0],[1, 2, 3]],[[1, 0, 0],[1,1,0],[1, 2, 3]],[[1, 0, 0],[1,1,0],[1, 2, 3]]])
print(soln.shape)

def animate(frame):
    for i, list in enumerate(rects):
        for j, rect in enumerate(list):
            rect.set_height(soln[i, frame, j])
    return rects

fig, axs = plt.subplots(1, 3)
xs = range(0, 3)
rects = []
for i in range(soln.shape[0]):
    rects.append(axs[i].bar(xs, soln[i, 0, :]))
ani = animation.FuncAnimation(fig, animate, blit=True, repeat=False)

标签: pythonmatplotlibmatplotlib-animation

解决方案


推荐阅读