2016-10-14 169 views
3

我有一个时间依赖的矩阵,我想将动画演变为动画。matplotlib中的动画matshow函数

我的代码如下:

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() 

然而,当我运行它,我总是得到以下错误:draw_artist can only be used after an initial draw which caches the render。我不知道这个错误来自哪里,也不知道如何解决它。 我已阅读this answerthis article但仍然不知道为什么我的代码不起作用。

任何帮助表示赞赏,谢谢!

回答

2

您非常接近工作解决方案。要么改变

plot = plt.matshow(data[0]) 

plot = plt.matshow(data[0], fignum=0) 

或使用

plot = plt.imshow(data[0]) 

代替。


在这里使用plt.matshow(data[0])的问题是,它creates a new figure如果fignum参数留空(即默认等于None)。 由于fig = plt.figure()被调用,并且fig传递给FuncAnimation,所以最后得到两个数字,一个结果为plt.matshow,另一个结果为FuncAnimationFuncAnimation正在绘制的数字未找到初始绘制,因此它会增加

AttributeError: draw_artist can only be used after an initial draw which caches the render