matplotlib 中的动画 matshow 函数

Vic*_*ven 5 python animation matplotlib

我有一个与时间相关的矩阵,我想将演变绘制为动画。

我的代码如下:

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


n_frames = 3 #Numero de ficheros que hemos generado
data = np.empty(n_frames, dtype=object) #Almacena los datos

#Leer todos los datos
for k in range(n_frames):
    data[k] = np.loadtxt("frame"+str(k))


fig = plt.figure()
plot =plt.matshow(data[0])

def init():
    plot.set_data(data[0])
    return plot

def update(j):
    plot.set_data(data[j])
    return [plot]


anim = FuncAnimation(fig, update, init_func = init, frames=n_frames, interval = 30, blit=True)

plt.show()
Run Code Online (Sandbox Code Playgroud)

但是,当我运行它时,我总是收到以下错误:draw_artist can only be used after an initial draw which caches the render。我不知道这个错误从何而来,也不知道如何解决。我已经阅读了这个答案这篇文章,但仍然不知道为什么我的代码不起作用。

任何帮助表示感谢,谢谢!

unu*_*tbu 6

您已经非常接近可行的解决方案了。要么改变

plot = plt.matshow(data[0])
Run Code Online (Sandbox Code Playgroud)

plot = plt.matshow(data[0], fignum=0)
Run Code Online (Sandbox Code Playgroud)

或使用

plot = plt.imshow(data[0])
Run Code Online (Sandbox Code Playgroud)

反而。


此处使用的问题plt.matshow(data[0])是,如果参数留空(即默认等于),它会创建一个新图形。由于被调用并且被传递给,您最终会得到两个数字,一个是 的结果,另一个是由 绘制的空白数字。正在绘制的图形找不到初始绘制,因此它会升高fignumNonefig = plt.figure()figFuncAnimationplt.matshowFuncAnimationFuncAnimation

AttributeError: draw_artist can only be used after an initial draw which caches the render
Run Code Online (Sandbox Code Playgroud)